diff --git a/lsp-test/bench/SimpleBench.hs b/lsp-test/bench/SimpleBench.hs index 72d868e2e..276cbbbf4 100644 --- a/lsp-test/bench/SimpleBench.hs +++ b/lsp-test/bench/SimpleBench.hs @@ -1,10 +1,12 @@ {-# LANGUAGE RankNTypes #-} -{-# LANGUAGE GADTs, OverloadedStrings #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE DuplicateRecordFields #-} module Main where import Language.LSP.Server import qualified Language.LSP.Test as Test -import Language.LSP.Types +import Language.LSP.Types hiding (options) import Control.Monad.IO.Class import Control.Monad import System.Process @@ -15,16 +17,16 @@ import Data.IORef handlers :: Handlers (LspM ()) handlers = mconcat - [ requestHandler STextDocumentHover $ \req responder -> do - let RequestMessage _ _ _ (HoverParams _doc pos _workDone) = req + [ requestHandler SMethod_TextDocumentHover $ \req responder -> do + let TRequestMessage _ _ _ (HoverParams _doc pos _workDone) = req Position _l _c' = pos rsp = Hover ms (Just range) - ms = HoverContents $ markedUpContent "lsp-demo-simple-server" "Hello world" + ms = InL $ markedUpContent "lsp-demo-simple-server" "Hello world" range = Range pos pos - responder (Right $ Just rsp) - , requestHandler STextDocumentDefinition $ \req responder -> do - let RequestMessage _ _ _ (DefinitionParams (TextDocumentIdentifier doc) pos _ _) = req - responder (Right $ InL $ Location doc $ Range pos pos) + responder (Right $ InL rsp) + , requestHandler SMethod_TextDocumentDefinition $ \req responder -> do + let TRequestMessage _ _ _ (DefinitionParams (TextDocumentIdentifier doc) pos _ _) = req + responder (Right $ InL $ Definition $ InL $ Location doc $ Range pos pos) ] server :: ServerDefinition () @@ -54,9 +56,9 @@ main = do replicateM_ n $ do n <- liftIO $ readIORef i liftIO $ when (n `mod` 1000 == 0) $ putStrLn $ show n - ResponseMessage{_result=Right (Just _)} <- Test.request STextDocumentHover $ + TResponseMessage{_result=Right (InL _)} <- Test.request SMethod_TextDocumentHover $ HoverParams (TextDocumentIdentifier $ Uri "test") (Position 1 100) Nothing - ResponseMessage{_result=Right (InL _)} <- Test.request STextDocumentDefinition $ + TResponseMessage{_result=Right (InL _)} <- Test.request SMethod_TextDocumentDefinition $ DefinitionParams (TextDocumentIdentifier $ Uri "test") (Position 1000 100) Nothing Nothing liftIO $ modifyIORef' i (+1) diff --git a/lsp-test/example/Test.hs b/lsp-test/example/Test.hs index 7763edb70..222ccd58e 100644 --- a/lsp-test/example/Test.hs +++ b/lsp-test/example/Test.hs @@ -11,7 +11,7 @@ main = runSession "lsp-demo-reactor-server" fullCaps "test/data/" $ do skipManyTill loggingNotification (count 1 publishDiagnosticsNotification) -- Send requests and notifications and receive responses - rsp <- request STextDocumentDocumentSymbol $ + rsp <- request SMethod_TextDocumentDocumentSymbol $ DocumentSymbolParams Nothing Nothing doc liftIO $ print rsp diff --git a/lsp-test/func-test/FuncTest.hs b/lsp-test/func-test/FuncTest.hs index 46016423a..51f7f7970 100644 --- a/lsp-test/func-test/FuncTest.hs +++ b/lsp-test/func-test/FuncTest.hs @@ -4,8 +4,7 @@ module Main where import Language.LSP.Server import qualified Language.LSP.Test as Test -import Language.LSP.Types -import Language.LSP.Types.Lens hiding (options) +import Language.LSP.Types hiding (options, error) import Control.Monad.IO.Class import System.IO import Control.Monad @@ -41,7 +40,7 @@ main = hspec $ do handlers :: MVar () -> Handlers (LspM ()) handlers killVar = - notificationHandler SInitialized $ \noti -> do + notificationHandler SMethod_Initialized $ \noti -> do tid <- withRunInIO $ \runInIO -> forkIO $ runInIO $ withProgress "Doing something" NotCancellable $ \updater -> @@ -55,20 +54,16 @@ main = hspec $ do Test.runSessionWithHandles hinWrite houtRead Test.defaultConfig Test.fullCaps "." $ do -- First make sure that we get a $/progress begin notification skipManyTill Test.anyMessage $ do - x <- Test.message SProgress - let isBegin (Begin _) = True - isBegin _ = False - guard $ isBegin $ x ^. params . value + x <- Test.message SMethod_Progress + guard $ has (params . value . _workDoneProgressBegin) x -- Then kill the thread liftIO $ putMVar killVar () -- Then make sure we still get a $/progress end notification skipManyTill Test.anyMessage $ do - x <- Test.message SProgress - let isEnd (End _) = True - isEnd _ = False - guard $ isEnd $ x ^. params . value + x <- Test.message SMethod_Progress + guard $ has (params . value . _workDoneProgressEnd) x describe "workspace folders" $ it "keeps track of open workspace folders" $ do @@ -77,9 +72,9 @@ main = hspec $ do countVar <- newMVar 0 - let wf0 = WorkspaceFolder "one" "Starter workspace" - wf1 = WorkspaceFolder "/foo/bar" "My workspace" - wf2 = WorkspaceFolder "/foo/baz" "My other workspace" + let wf0 = WorkspaceFolder (filePathToUri "one") "Starter workspace" + wf1 = WorkspaceFolder (filePathToUri "/foo/bar") "My workspace" + wf2 = WorkspaceFolder (filePathToUri "/foo/baz") "My other workspace" definition = ServerDefinition { onConfigurationChange = const $ const $ Right () @@ -92,10 +87,10 @@ main = hspec $ do handlers :: Handlers (LspM ()) handlers = mconcat - [ notificationHandler SInitialized $ \noti -> do + [ notificationHandler SMethod_Initialized $ \noti -> do wfs <- fromJust <$> getWorkspaceFolders liftIO $ wfs `shouldContain` [wf0] - , notificationHandler SWorkspaceDidChangeWorkspaceFolders $ \noti -> do + , notificationHandler SMethod_WorkspaceDidChangeWorkspaceFolders $ \noti -> do i <- liftIO $ modifyMVar countVar (\i -> pure (i + 1, i)) wfs <- fromJust <$> getWorkspaceFolders liftIO $ case i of @@ -116,11 +111,9 @@ main = hspec $ do } changeFolders add rmv = - let addedFolders = List add - removedFolders = List rmv - ev = WorkspaceFoldersChangeEvent addedFolders removedFolders + let ev = WorkspaceFoldersChangeEvent add rmv ps = DidChangeWorkspaceFoldersParams ev - in Test.sendNotification SWorkspaceDidChangeWorkspaceFolders ps + in Test.sendNotification SMethod_WorkspaceDidChangeWorkspaceFolders ps Test.runSessionWithHandles hinWrite houtRead config Test.fullCaps "." $ do changeFolders [wf1] [] diff --git a/lsp-test/lsp-test.cabal b/lsp-test/lsp-test.cabal index 115d3a527..97c28f73d 100644 --- a/lsp-test/lsp-test.cabal +++ b/lsp-test/lsp-test.cabal @@ -58,8 +58,8 @@ library , mtl < 2.4 , parser-combinators >= 1.2 , process >= 1.6 + , row-types , text - , transformers , unordered-containers , some if os(windows) @@ -83,6 +83,7 @@ test-suite tests ghc-options: -W build-depends: base >= 4.10 && < 5 , hspec + , containers , lens , lsp == 1.6.* , lsp-test diff --git a/lsp-test/src/Language/LSP/Test.hs b/lsp-test/src/Language/LSP/Test.hs index 8d977f321..e8a8bf4c9 100644 --- a/lsp-test/src/Language/LSP/Test.hs +++ b/lsp-test/src/Language/LSP/Test.hs @@ -113,15 +113,13 @@ import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Text.IO as T -import Data.Aeson +import Data.Aeson hiding (Null) import Data.Default -import qualified Data.HashMap.Strict as HashMap import Data.List import Data.Maybe import Language.LSP.Types -import Language.LSP.Types.Lens hiding - (id, capabilities, message, executeCommand, applyEdit, rename, to) -import qualified Language.LSP.Types.Lens as LSP + hiding (capabilities, message, executeCommand, applyEdit, rename, to, id) +import qualified Language.LSP.Types as LSP import qualified Language.LSP.Types.Capabilities as C import Language.LSP.VFS import Language.LSP.Test.Compat @@ -147,7 +145,7 @@ import Control.Monad.State (execState) -- > params = TextDocumentPositionParams doc -- > hover <- request STextdocumentHover params runSession :: String -- ^ The command to run the server. - -> C.ClientCapabilities -- ^ The capabilities that the client should declare. + -> ClientCapabilities -- ^ The capabilities that the client should declare. -> FilePath -- ^ The filepath to the root directory for the session. -> Session a -- ^ The session to run. -> IO a @@ -156,7 +154,7 @@ runSession = runSessionWithConfig def -- | Starts a new session with a custom configuration. runSessionWithConfig :: SessionConfig -- ^ Configuration options for the session. -> String -- ^ The command to run the server. - -> C.ClientCapabilities -- ^ The capabilities that the client should declare. + -> ClientCapabilities -- ^ The capabilities that the client should declare. -> FilePath -- ^ The filepath to the root directory for the session. -> Session a -- ^ The session to run. -> IO a @@ -166,7 +164,7 @@ runSessionWithConfig = runSessionWithConfigCustomProcess id runSessionWithConfigCustomProcess :: (CreateProcess -> CreateProcess) -- ^ Tweak the 'CreateProcess' used to start the server. -> SessionConfig -- ^ Configuration options for the session. -> String -- ^ The command to run the server. - -> C.ClientCapabilities -- ^ The capabilities that the client should declare. + -> ClientCapabilities -- ^ The capabilities that the client should declare. -> FilePath -- ^ The filepath to the root directory for the session. -> Session a -- ^ The session to run. -> IO a @@ -188,7 +186,7 @@ runSessionWithConfigCustomProcess modifyCreateProcess config' serverExe caps roo runSessionWithHandles :: Handle -- ^ The input handle -> Handle -- ^ The output handle -> SessionConfig - -> C.ClientCapabilities -- ^ The capabilities that the client should declare. + -> ClientCapabilities -- ^ The capabilities that the client should declare. -> FilePath -- ^ The filepath to the root directory for the session. -> Session a -- ^ The session to run. -> IO a @@ -199,7 +197,7 @@ runSessionWithHandles' :: Maybe ProcessHandle -> Handle -- ^ The input handle -> Handle -- ^ The output handle -> SessionConfig - -> C.ClientCapabilities -- ^ The capabilities that the client should declare. + -> ClientCapabilities -- ^ The capabilities that the client should declare. -> FilePath -- ^ The filepath to the root directory for the session. -> Session a -- ^ The session to run. -> IO a @@ -212,21 +210,22 @@ runSessionWithHandles' serverProc serverIn serverOut config' caps rootDir sessio let initializeParams = InitializeParams Nothing -- Narrowing to Int32 here, but it's unlikely that a PID will -- be outside the range - (Just $ fromIntegral pid) + (InL $ fromIntegral pid) (Just lspTestClientInfo) (Just $ T.pack absRootDir) - (Just $ filePathToUri absRootDir) - (lspConfig config') + Nothing + (InL $ filePathToUri absRootDir) caps - (Just TraceOff) - (List <$> initialWorkspaceFolders config) + (lspConfig config') + (Just $ InL AString) + (fmap InL $ initialWorkspaceFolders config) runSession' serverIn serverOut serverProc listenServer config caps rootDir exitServer $ do -- Wrap the session around initialize and shutdown calls - initReqId <- sendRequest SInitialize initializeParams + initReqId <- sendRequest SMethod_Initialize initializeParams -- Because messages can be sent in between the request and response, -- collect them and then... - (inBetween, initRspMsg) <- manyTill_ anyMessage (responseForId SInitialize initReqId) + (inBetween, initRspMsg) <- manyTill_ anyMessage (responseForId SMethod_Initialize initReqId) case initRspMsg ^. LSP.result of Left error -> liftIO $ putStrLn ("Error while initializing: " ++ show error) @@ -234,10 +233,10 @@ runSessionWithHandles' serverProc serverIn serverOut config' caps rootDir sessio initRspVar <- initRsp <$> ask liftIO $ putMVar initRspVar initRspMsg - sendNotification SInitialized (Just InitializedParams) + sendNotification SMethod_Initialized InitializedParams case lspConfig config of - Just cfg -> sendNotification SWorkspaceDidChangeConfiguration (DidChangeConfigurationParams cfg) + Just cfg -> sendNotification SMethod_WorkspaceDidChangeConfiguration (DidChangeConfigurationParams cfg) Nothing -> return () -- ... relay them back to the user Session so they can match on them! @@ -251,7 +250,7 @@ runSessionWithHandles' serverProc serverIn serverOut config' caps rootDir sessio where -- | Asks the server to shutdown and exit politely exitServer :: Session () - exitServer = request_ SShutdown Empty >> sendNotification SExit Empty + exitServer = request_ SMethod_Shutdown Nothing >> sendNotification SMethod_Exit Nothing -- | Listens to the server output until the shutdown ACK, -- makes sure it matches the record and signals any semaphores @@ -264,17 +263,17 @@ runSessionWithHandles' serverProc serverIn serverOut config' caps rootDir sessio writeChan (messageChan context) (ServerMessage msg) case msg of - (FromServerRsp SShutdown _) -> return () + (FromServerRsp SMethod_Shutdown _) -> return () _ -> listenServer serverOut context -- | Is this message allowed to be sent by the server between the intialize -- request and response? -- https://microsoft.github.io/language-server-protocol/specifications/specification-3-15/#initialize checkLegalBetweenMessage :: FromServerMessage -> Session () - checkLegalBetweenMessage (FromServerMess SWindowShowMessage _) = pure () - checkLegalBetweenMessage (FromServerMess SWindowLogMessage _) = pure () - checkLegalBetweenMessage (FromServerMess STelemetryEvent _) = pure () - checkLegalBetweenMessage (FromServerMess SWindowShowMessageRequest _) = pure () + checkLegalBetweenMessage (FromServerMess SMethod_WindowShowMessage _) = pure () + checkLegalBetweenMessage (FromServerMess SMethod_WindowLogMessage _) = pure () + checkLegalBetweenMessage (FromServerMess SMethod_TelemetryEvent _) = pure () + checkLegalBetweenMessage (FromServerMess SMethod_WindowShowMessageRequest _) = pure () checkLegalBetweenMessage msg = throw (IllegalInitSequenceMessage msg) -- | Check environment variables to override the config @@ -299,7 +298,7 @@ documentContents doc = do -- and returns the new content getDocumentEdit :: TextDocumentIdentifier -> Session T.Text getDocumentEdit doc = do - req <- message SWorkspaceApplyEdit + req <- message SMethod_WorkspaceApplyEdit unless (checkDocumentChanges req || checkChanges req) $ liftIO $ throw (IncorrectApplyEditRequest (show req)) @@ -314,7 +313,7 @@ getDocumentEdit doc = do Nothing -> False checkChanges req = let mMap = req ^. params . edit . changes - in maybe False (HashMap.member (doc ^. uri)) mMap + in maybe False (Map.member (doc ^. uri)) mMap -- | Sends a request to the server and waits for its response. -- Will skip any messages in between the request and the response @@ -322,11 +321,11 @@ getDocumentEdit doc = do -- rsp <- request STextDocumentDocumentSymbol params -- @ -- Note: will skip any messages in between the request and the response. -request :: SClientMethod m -> MessageParams m -> Session (ResponseMessage m) +request :: SClientMethod m -> MessageParams m -> Session (TResponseMessage m) request m = sendRequest m >=> skipManyTill anyMessage . responseForId m -- | The same as 'sendRequest', but discard the response. -request_ :: SClientMethod (m :: Method FromClient Request) -> MessageParams m -> Session () +request_ :: SClientMethod (m :: Method ClientToServer Request) -> MessageParams m -> Session () request_ p = void . request p -- | Sends a request to the server. Unlike 'request', this doesn't wait for the response. @@ -339,7 +338,7 @@ sendRequest method params = do modify $ \c -> c { curReqId = idn+1 } let id = IdInt idn - let mess = RequestMessage "2.0" id method params + let mess = TRequestMessage "2.0" id method params -- Update the request map reqMap <- requestMap <$> ask @@ -353,27 +352,27 @@ sendRequest method params = do return id -- | Sends a notification to the server. -sendNotification :: SClientMethod (m :: Method FromClient Notification) -- ^ The notification method. +sendNotification :: SClientMethod (m :: Method ClientToServer Notification) -- ^ The notification method. -> MessageParams m -- ^ The notification parameters. -> Session () -- Open a virtual file if we send a did open text document notification -sendNotification STextDocumentDidOpen params = do - let n = NotificationMessage "2.0" STextDocumentDidOpen params +sendNotification SMethod_TextDocumentDidOpen params = do + let n = TNotificationMessage "2.0" SMethod_TextDocumentDidOpen params oldVFS <- vfs <$> get let newVFS = flip execState oldVFS $ openVFS mempty n modify (\s -> s { vfs = newVFS }) sendMessage n -- Close a virtual file if we send a close text document notification -sendNotification STextDocumentDidClose params = do - let n = NotificationMessage "2.0" STextDocumentDidClose params +sendNotification SMethod_TextDocumentDidClose params = do + let n = TNotificationMessage "2.0" SMethod_TextDocumentDidClose params oldVFS <- vfs <$> get let newVFS = flip execState oldVFS $ closeVFS mempty n modify (\s -> s { vfs = newVFS }) sendMessage n -sendNotification STextDocumentDidChange params = do - let n = NotificationMessage "2.0" STextDocumentDidChange params +sendNotification SMethod_TextDocumentDidChange params = do + let n = TNotificationMessage "2.0" SMethod_TextDocumentDidChange params oldVFS <- vfs <$> get let newVFS = flip execState oldVFS $ changeFromClientVFS mempty n modify (\s -> s { vfs = newVFS }) @@ -381,17 +380,17 @@ sendNotification STextDocumentDidChange params = do sendNotification method params = case splitClientMethod method of - IsClientNot -> sendMessage (NotificationMessage "2.0" method params) - IsClientEither -> sendMessage (NotMess $ NotificationMessage "2.0" method params) + IsClientNot -> sendMessage (TNotificationMessage "2.0" method params) + IsClientEither -> sendMessage (NotMess $ TNotificationMessage "2.0" method params) -- | Sends a response to the server. -sendResponse :: ToJSON (ResponseResult m) => ResponseMessage m -> Session () +sendResponse :: (ToJSON (MessageResult m), ToJSON (ErrorData m)) => TResponseMessage m -> Session () sendResponse = sendMessage -- | Returns the initialize response that was received from the server. -- The initialize requests and responses are not included the session, -- so if you need to test it use this. -initializeResponse :: Session (ResponseMessage Initialize) +initializeResponse :: Session (TResponseMessage Method_Initialize) initializeResponse = ask >>= (liftIO . readMVar) . initRsp -- | /Creates/ a new text document. This is different from 'openDoc' @@ -412,14 +411,16 @@ createDoc file languageId contents = do rootDir <- asks rootDir caps <- asks sessionCapabilities absFile <- liftIO $ canonicalizePath (rootDir file) - let pred :: SomeRegistration -> [Registration WorkspaceDidChangeWatchedFiles] - pred (SomeRegistration r@(Registration _ SWorkspaceDidChangeWatchedFiles _)) = [r] + let pred :: SomeRegistration -> [TRegistration Method_WorkspaceDidChangeWatchedFiles] + pred (SomeRegistration r@(TRegistration _ SMethod_WorkspaceDidChangeWatchedFiles _)) = [r] pred _ = mempty regs = concatMap pred $ Map.elems dynCaps watchHits :: FileSystemWatcher -> Bool - watchHits (FileSystemWatcher pattern kind) = + watchHits (FileSystemWatcher (GlobPattern (InL (Pattern pattern))) kind) = -- If WatchKind is excluded, defaults to all true as per spec - fileMatches (T.unpack pattern) && createHits (fromMaybe (WatchKind True True True) kind) + fileMatches (T.unpack pattern) && createHits (fromMaybe WatchKind_Create kind) + -- TODO: Relative patterns + watchHits _ = False fileMatches pattern = Glob.match (Glob.compile pattern) relOrAbs -- If the pattern is absolute then match against the absolute fp @@ -427,9 +428,10 @@ createDoc file languageId contents = do | isAbsolute pattern = absFile | otherwise = file - createHits (WatchKind create _ _) = create + createHits WatchKind_Create = True + createHits _ = False - regHits :: Registration WorkspaceDidChangeWatchedFiles -> Bool + regHits :: TRegistration Method_WorkspaceDidChangeWatchedFiles -> Bool regHits reg = foldl' (\acc w -> acc || watchHits w) False (reg ^. registerOptions . _Just . watchers) clientCapsSupports = @@ -438,8 +440,8 @@ createDoc file languageId contents = do shouldSend = clientCapsSupports && foldl' (\acc r -> acc || regHits r) False regs when shouldSend $ - sendNotification SWorkspaceDidChangeWatchedFiles $ DidChangeWatchedFilesParams $ - List [ FileEvent (filePathToUri (rootDir file)) FcCreated ] + sendNotification SMethod_WorkspaceDidChangeWatchedFiles $ DidChangeWatchedFilesParams $ + [ FileEvent (filePathToUri (rootDir file)) FileChangeType_Created ] openDoc' file languageId contents -- | Opens a text document that /exists on disk/, and sends a @@ -459,21 +461,21 @@ openDoc' file languageId contents = do let fp = rootDir context file uri = filePathToUri fp item = TextDocumentItem uri languageId 0 contents - sendNotification STextDocumentDidOpen (DidOpenTextDocumentParams item) + sendNotification SMethod_TextDocumentDidOpen (DidOpenTextDocumentParams item) pure $ TextDocumentIdentifier uri -- | Closes a text document and sends a textDocument/didOpen notification to the server. closeDoc :: TextDocumentIdentifier -> Session () closeDoc docId = do let params = DidCloseTextDocumentParams (TextDocumentIdentifier (docId ^. uri)) - sendNotification STextDocumentDidClose params + sendNotification SMethod_TextDocumentDidClose params -- | Changes a text document and sends a textDocument/didOpen notification to the server. changeDoc :: TextDocumentIdentifier -> [TextDocumentContentChangeEvent] -> Session () changeDoc docId changes = do verDoc <- getVersionedDoc docId - let params = DidChangeTextDocumentParams (verDoc & version . non 0 +~ 1) (List changes) - sendNotification STextDocumentDidChange params + let params = DidChangeTextDocumentParams (verDoc & version +~ 1) changes + sendNotification SMethod_TextDocumentDidChange params -- | Gets the Uri for the file corrected to the session directory. getDocUri :: FilePath -> Session Uri @@ -485,8 +487,8 @@ getDocUri file = do -- | Waits for diagnostics to be published and returns them. waitForDiagnostics :: Session [Diagnostic] waitForDiagnostics = do - diagsNot <- skipManyTill anyMessage (message STextDocumentPublishDiagnostics) - let (List diags) = diagsNot ^. params . LSP.diagnostics + diagsNot <- skipManyTill anyMessage (message SMethod_TextDocumentPublishDiagnostics) + let diags = diagsNot ^. params . LSP.diagnostics return diags -- | The same as 'waitForDiagnostics', but will only match a specific @@ -507,27 +509,29 @@ waitForDiagnosticsSource src = do -- returned. noDiagnostics :: Session () noDiagnostics = do - diagsNot <- message STextDocumentPublishDiagnostics - when (diagsNot ^. params . LSP.diagnostics /= List []) $ liftIO $ throw UnexpectedDiagnostics + diagsNot <- message SMethod_TextDocumentPublishDiagnostics + when (diagsNot ^. params . LSP.diagnostics /= []) $ liftIO $ throw UnexpectedDiagnostics -- | Returns the symbols in a document. -getDocumentSymbols :: TextDocumentIdentifier -> Session (Either [DocumentSymbol] [SymbolInformation]) +getDocumentSymbols :: TextDocumentIdentifier -> Session (Either [SymbolInformation] [DocumentSymbol]) getDocumentSymbols doc = do - ResponseMessage _ rspLid res <- request STextDocumentDocumentSymbol (DocumentSymbolParams Nothing Nothing doc) + TResponseMessage _ rspLid res <- request SMethod_TextDocumentDocumentSymbol (DocumentSymbolParams Nothing Nothing doc) case res of - Right (InL (List xs)) -> return (Left xs) - Right (InR (List xs)) -> return (Right xs) - Left err -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) err) + Right (InL xs) -> return (Left xs) + Right (InR (InL xs)) -> return (Right xs) + Right (InR (InR _)) -> return (Right []) + Left err -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) (toUntypedResponseError err)) -- | Returns the code actions in the specified range. getCodeActions :: TextDocumentIdentifier -> Range -> Session [Command |? CodeAction] getCodeActions doc range = do ctx <- getCodeActionContextInRange doc range - rsp <- request STextDocumentCodeAction (CodeActionParams Nothing Nothing doc range ctx) + rsp <- request SMethod_TextDocumentCodeAction (CodeActionParams Nothing Nothing doc range ctx) case rsp ^. result of - Right (List xs) -> return xs - Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. LSP.id) error) + Right (InL xs) -> return xs + Right (InR _) -> return [] + Left error -> throw (UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. LSP.id) (toUntypedResponseError error)) -- | Returns all the code actions in a document by -- querying the code actions at each of the current @@ -541,11 +545,12 @@ getAllCodeActions doc = do where go :: CodeActionContext -> [Command |? CodeAction] -> Diagnostic -> Session [Command |? CodeAction] go ctx acc diag = do - ResponseMessage _ rspLid res <- request STextDocumentCodeAction (CodeActionParams Nothing Nothing doc (diag ^. range) ctx) + TResponseMessage _ rspLid res <- request SMethod_TextDocumentCodeAction (CodeActionParams Nothing Nothing doc (diag ^. range) ctx) case res of - Left e -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) e) - Right (List cmdOrCAs) -> pure (acc ++ cmdOrCAs) + Left e -> throw (UnexpectedResponseError (SomeLspId $ fromJust rspLid) (toUntypedResponseError e)) + Right (InL cmdOrCAs) -> pure (acc ++ cmdOrCAs) + Right (InR _) -> pure acc getCodeActionContextInRange :: TextDocumentIdentifier -> Range -> Session CodeActionContext getCodeActionContextInRange doc caRange = do @@ -553,7 +558,7 @@ getCodeActionContextInRange doc caRange = do let diags = [ d | d@Diagnostic{_range=range} <- curDiags , overlappingRange caRange range ] - return $ CodeActionContext (List diags) Nothing + return $ CodeActionContext diags Nothing Nothing where overlappingRange :: Range -> Range -> Bool overlappingRange (Range s e) range = @@ -570,7 +575,7 @@ getCodeActionContextInRange doc caRange = do getCodeActionContext :: TextDocumentIdentifier -> Session CodeActionContext getCodeActionContext doc = do curDiags <- getCurrentDiagnostics doc - return $ CodeActionContext (List curDiags) Nothing + return $ CodeActionContext curDiags Nothing Nothing -- | Returns the current diagnostics that have been sent to the client. -- Note that this does not wait for more to come in. @@ -586,7 +591,7 @@ executeCommand :: Command -> Session () executeCommand cmd = do let args = decode $ encode $ fromJust $ cmd ^. arguments execParams = ExecuteCommandParams Nothing (cmd ^. command) args - void $ sendRequest SWorkspaceExecuteCommand execParams + void $ sendRequest SMethod_WorkspaceExecuteCommand execParams -- | Executes a code action. -- Matching with the specification, if a code action @@ -600,15 +605,17 @@ executeCodeAction action = do where handleEdit :: WorkspaceEdit -> Session () handleEdit e = -- Its ok to pass in dummy parameters here as they aren't used - let req = RequestMessage "" (IdInt 0) SWorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing e) - in updateState (FromServerMess SWorkspaceApplyEdit req) + let req = TRequestMessage "" (IdInt 0) SMethod_WorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing e) + in updateState (FromServerMess SMethod_WorkspaceApplyEdit req) -- | Adds the current version to the document, as tracked by the session. getVersionedDoc :: TextDocumentIdentifier -> Session VersionedTextDocumentIdentifier getVersionedDoc (TextDocumentIdentifier uri) = do vfs <- vfs <$> get let ver = vfs ^? vfsMap . ix (toNormalizedUri uri) . to virtualFileVersion - return (VersionedTextDocumentIdentifier uri ver) + -- TODO: is this correct? Could return an OptionalVersionedTextDocumentIdentifier, + -- but that complicated callers... + return (VersionedTextDocumentIdentifier uri (fromMaybe 0 ver)) -- | Applys an edit to the document and returns the updated document version. applyEdit :: TextDocumentIdentifier -> TextEdit -> Session VersionedTextDocumentIdentifier @@ -618,22 +625,18 @@ applyEdit doc edit = do caps <- asks sessionCapabilities - let supportsDocChanges = fromMaybe False $ do - let mWorkspace = caps ^. LSP.workspace - C.WorkspaceClientCapabilities _ mEdit _ _ _ _ _ _ _ <- mWorkspace - C.WorkspaceEditClientCapabilities mDocChanges _ _ _ _ <- mEdit - mDocChanges + let supportsDocChanges = fromMaybe False $ caps ^? LSP.workspace . _Just . LSP.workspaceEdit . _Just . documentChanges . _Just let wEdit = if supportsDocChanges then - let docEdit = TextDocumentEdit verDoc (List [InL edit]) - in WorkspaceEdit Nothing (Just (List [InL docEdit])) Nothing + let docEdit = TextDocumentEdit (review _versionedTextDocumentIdentifier verDoc) [InL edit] + in WorkspaceEdit Nothing (Just [InL docEdit]) Nothing else - let changes = HashMap.singleton (doc ^. uri) (List [edit]) + let changes = Map.singleton (doc ^. uri) [edit] in WorkspaceEdit (Just changes) Nothing Nothing - let req = RequestMessage "" (IdInt 0) SWorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing wEdit) - updateState (FromServerMess SWorkspaceApplyEdit req) + let req = TRequestMessage "" (IdInt 0) SMethod_WorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing wEdit) + updateState (FromServerMess SMethod_WorkspaceApplyEdit req) -- version may have changed getVersionedDoc doc @@ -641,146 +644,139 @@ applyEdit doc edit = do -- | Returns the completions for the position in the document. getCompletions :: TextDocumentIdentifier -> Position -> Session [CompletionItem] getCompletions doc pos = do - rsp <- request STextDocumentCompletion (CompletionParams doc pos Nothing Nothing Nothing) + rsp <- request SMethod_TextDocumentCompletion (CompletionParams doc pos Nothing Nothing Nothing) case getResponseResult rsp of - InL (List items) -> return items - InR (CompletionList _ (List items)) -> return items + InL items -> return items + InR (InL c) -> return $ c ^. LSP.items + InR (InR _) -> return [] -- | Returns the references for the position in the document. getReferences :: TextDocumentIdentifier -- ^ The document to lookup in. -> Position -- ^ The position to lookup. -> Bool -- ^ Whether to include declarations as references. - -> Session (List Location) -- ^ The locations of the references. + -> Session [Location] -- ^ The locations of the references. getReferences doc pos inclDecl = let ctx = ReferenceContext inclDecl params = ReferenceParams doc pos Nothing Nothing ctx - in getResponseResult <$> request STextDocumentReferences params + in absorbNull . getResponseResult <$> request SMethod_TextDocumentReferences params -- | Returns the declarations(s) for the term at the specified position. getDeclarations :: TextDocumentIdentifier -- ^ The document the term is in. -> Position -- ^ The position the term is at. - -> Session ([Location] |? [LocationLink]) -getDeclarations = getDeclarationyRequest STextDocumentDeclaration DeclarationParams + -> Session (Declaration |? [DeclarationLink] |? Null) +getDeclarations doc pos = do + rsp <- request SMethod_TextDocumentDeclaration (DeclarationParams doc pos Nothing Nothing) + pure $ getResponseResult rsp -- | Returns the definition(s) for the term at the specified position. getDefinitions :: TextDocumentIdentifier -- ^ The document the term is in. -> Position -- ^ The position the term is at. - -> Session ([Location] |? [LocationLink]) -getDefinitions = getDeclarationyRequest STextDocumentDefinition DefinitionParams + -> Session (Definition |? [DefinitionLink] |? Null) +getDefinitions doc pos = do + rsp <- request SMethod_TextDocumentDefinition (DefinitionParams doc pos Nothing Nothing) + pure $ getResponseResult rsp -- | Returns the type definition(s) for the term at the specified position. getTypeDefinitions :: TextDocumentIdentifier -- ^ The document the term is in. -> Position -- ^ The position the term is at. - -> Session ([Location] |? [LocationLink]) -getTypeDefinitions = getDeclarationyRequest STextDocumentTypeDefinition TypeDefinitionParams + -> Session (Definition |? [DefinitionLink] |? Null) +getTypeDefinitions doc pos = do + rsp <- request SMethod_TextDocumentTypeDefinition (TypeDefinitionParams doc pos Nothing Nothing) + pure $ getResponseResult rsp -- | Returns the type definition(s) for the term at the specified position. getImplementations :: TextDocumentIdentifier -- ^ The document the term is in. -> Position -- ^ The position the term is at. - -> Session ([Location] |? [LocationLink]) -getImplementations = getDeclarationyRequest STextDocumentImplementation ImplementationParams - - -getDeclarationyRequest :: (ResponseResult m ~ (Location |? (List Location |? List LocationLink))) - => SClientMethod m - -> (TextDocumentIdentifier - -> Position - -> Maybe ProgressToken - -> Maybe ProgressToken - -> MessageParams m) - -> TextDocumentIdentifier - -> Position - -> Session ([Location] |? [LocationLink]) -getDeclarationyRequest method paramCons doc pos = do - let params = paramCons doc pos Nothing Nothing - rsp <- request method params - case getResponseResult rsp of - InL loc -> pure (InL [loc]) - InR (InL (List locs)) -> pure (InL locs) - InR (InR (List locLinks)) -> pure (InR locLinks) + -> Session (Definition |? [DefinitionLink] |? Null) +getImplementations doc pos = do + rsp <- request SMethod_TextDocumentImplementation (ImplementationParams doc pos Nothing Nothing) + pure $ getResponseResult rsp -- | Renames the term at the specified position. rename :: TextDocumentIdentifier -> Position -> String -> Session () rename doc pos newName = do - let params = RenameParams doc pos Nothing (T.pack newName) - rsp <- request STextDocumentRename params + let params = RenameParams Nothing doc pos (T.pack newName) + rsp <- request SMethod_TextDocumentRename params let wEdit = getResponseResult rsp - req = RequestMessage "" (IdInt 0) SWorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing wEdit) - updateState (FromServerMess SWorkspaceApplyEdit req) + case nullToMaybe wEdit of + Just e -> do + let req = TRequestMessage "" (IdInt 0) SMethod_WorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing e) + updateState (FromServerMess SMethod_WorkspaceApplyEdit req) + Nothing -> pure () -- | Returns the hover information at the specified position. getHover :: TextDocumentIdentifier -> Position -> Session (Maybe Hover) getHover doc pos = let params = HoverParams doc pos Nothing - in getResponseResult <$> request STextDocumentHover params + in nullToMaybe . getResponseResult <$> request SMethod_TextDocumentHover params -- | Returns the highlighted occurrences of the term at the specified position -getHighlights :: TextDocumentIdentifier -> Position -> Session (List DocumentHighlight) +getHighlights :: TextDocumentIdentifier -> Position -> Session [DocumentHighlight] getHighlights doc pos = let params = DocumentHighlightParams doc pos Nothing Nothing - in getResponseResult <$> request STextDocumentDocumentHighlight params + in absorbNull . getResponseResult <$> request SMethod_TextDocumentDocumentHighlight params -- | Checks the response for errors and throws an exception if needed. -- Returns the result if successful. -getResponseResult :: ResponseMessage m -> ResponseResult m +getResponseResult :: (ToJSON (ErrorData m)) => TResponseMessage m -> MessageResult m getResponseResult rsp = case rsp ^. result of Right x -> x - Left err -> throw $ UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. LSP.id) err + Left err -> throw $ UnexpectedResponseError (SomeLspId $ fromJust $ rsp ^. LSP.id) (toUntypedResponseError err) -- | Applies formatting to the specified document. formatDoc :: TextDocumentIdentifier -> FormattingOptions -> Session () formatDoc doc opts = do let params = DocumentFormattingParams Nothing doc opts - edits <- getResponseResult <$> request STextDocumentFormatting params + edits <- absorbNull . getResponseResult <$> request SMethod_TextDocumentFormatting params applyTextEdits doc edits -- | Applies formatting to the specified range in a document. formatRange :: TextDocumentIdentifier -> FormattingOptions -> Range -> Session () formatRange doc opts range = do let params = DocumentRangeFormattingParams Nothing doc range opts - edits <- getResponseResult <$> request STextDocumentRangeFormatting params + edits <- absorbNull . getResponseResult <$> request SMethod_TextDocumentRangeFormatting params applyTextEdits doc edits -applyTextEdits :: TextDocumentIdentifier -> List TextEdit -> Session () +applyTextEdits :: TextDocumentIdentifier -> [TextEdit] -> Session () applyTextEdits doc edits = - let wEdit = WorkspaceEdit (Just (HashMap.singleton (doc ^. uri) edits)) Nothing Nothing + let wEdit = WorkspaceEdit (Just (Map.singleton (doc ^. uri) edits)) Nothing Nothing -- Send a dummy message to updateState so it can do bookkeeping - req = RequestMessage "" (IdInt 0) SWorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing wEdit) - in updateState (FromServerMess SWorkspaceApplyEdit req) + req = TRequestMessage "" (IdInt 0) SMethod_WorkspaceApplyEdit (ApplyWorkspaceEditParams Nothing wEdit) + in updateState (FromServerMess SMethod_WorkspaceApplyEdit req) -- | Returns the code lenses for the specified document. getCodeLenses :: TextDocumentIdentifier -> Session [CodeLens] getCodeLenses tId = do - rsp <- request STextDocumentCodeLens (CodeLensParams Nothing Nothing tId) - case getResponseResult rsp of - List res -> pure res + rsp <- request SMethod_TextDocumentCodeLens (CodeLensParams Nothing Nothing tId) + pure $ absorbNull $ getResponseResult rsp -- | Pass a param and return the response from `prepareCallHierarchy` prepareCallHierarchy :: CallHierarchyPrepareParams -> Session [CallHierarchyItem] -prepareCallHierarchy = resolveRequestWithListResp STextDocumentPrepareCallHierarchy +prepareCallHierarchy = resolveRequestWithListResp SMethod_TextDocumentPrepareCallHierarchy incomingCalls :: CallHierarchyIncomingCallsParams -> Session [CallHierarchyIncomingCall] -incomingCalls = resolveRequestWithListResp SCallHierarchyIncomingCalls +incomingCalls = resolveRequestWithListResp SMethod_CallHierarchyIncomingCalls outgoingCalls :: CallHierarchyOutgoingCallsParams -> Session [CallHierarchyOutgoingCall] -outgoingCalls = resolveRequestWithListResp SCallHierarchyOutgoingCalls +outgoingCalls = resolveRequestWithListResp SMethod_CallHierarchyOutgoingCalls -- | Send a request and receive a response with list. -resolveRequestWithListResp :: (ResponseResult m ~ Maybe (List a)) - => SClientMethod m -> MessageParams m -> Session [a] +resolveRequestWithListResp :: forall (m :: Method ClientToServer Request) a + . (ToJSON (ErrorData m), MessageResult m ~ [a] |? Null) + => SMethod m + -> MessageParams m + -> Session [a] resolveRequestWithListResp method params = do rsp <- request method params - case getResponseResult rsp of - Nothing -> pure [] - Just (List x) -> pure x + pure $ absorbNull $ getResponseResult rsp -- | Pass a param and return the response from `prepareCallHierarchy` -getSemanticTokens :: TextDocumentIdentifier -> Session (Maybe SemanticTokens) +getSemanticTokens :: TextDocumentIdentifier -> Session (SemanticTokens |? Null) getSemanticTokens doc = do let params = SemanticTokensParams Nothing Nothing doc - rsp <- request STextDocumentSemanticTokensFull params + rsp <- request SMethod_TextDocumentSemanticTokensFull params pure $ getResponseResult rsp -- | Returns a list of capabilities that the server has requested to /dynamically/ diff --git a/lsp-test/src/Language/LSP/Test/Compat.hs b/lsp-test/src/Language/LSP/Test/Compat.hs index 8055d7c59..f92c416cb 100644 --- a/lsp-test/src/Language/LSP/Test/Compat.hs +++ b/lsp-test/src/Language/LSP/Test/Compat.hs @@ -1,13 +1,18 @@ -{-# LANGUAGE CPP, OverloadedStrings #-} +{-# LANGUAGE CPP #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE OverloadedLabels #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE DataKinds #-} -- For some reason ghc warns about not using -- Control.Monad.IO.Class but it's needed for -- MonadIO {-# OPTIONS_GHC -Wunused-imports #-} module Language.LSP.Test.Compat where +import Data.Row import Data.Maybe +import qualified Data.Text as T import System.IO -import Language.LSP.Types #if MIN_VERSION_process(1,6,3) -- We have to hide cleanupProcess for process-1.6.3.0 @@ -115,6 +120,5 @@ withCreateProcess c action = #endif - -lspTestClientInfo :: ClientInfo -lspTestClientInfo = ClientInfo "lsp-test" (Just CURRENT_PACKAGE_VERSION) +lspTestClientInfo :: Rec ("name" .== T.Text .+ "version" .== Maybe T.Text) +lspTestClientInfo = #name .== "lsp-test" .+ #version .== (Just CURRENT_PACKAGE_VERSION) diff --git a/lsp-test/src/Language/LSP/Test/Decoding.hs b/lsp-test/src/Language/LSP/Test/Decoding.hs index c5cefd632..360986bf3 100644 --- a/lsp-test/src/Language/LSP/Test/Decoding.hs +++ b/lsp-test/src/Language/LSP/Test/Decoding.hs @@ -17,8 +17,7 @@ import qualified Data.ByteString.Lazy.Char8 as B import Data.Maybe import System.IO import System.IO.Error -import Language.LSP.Types -import Language.LSP.Types.Lens +import Language.LSP.Types hiding (error) import Language.LSP.Test.Exceptions import Data.IxMap @@ -51,7 +50,7 @@ getHeaders h = do | isEOFError e = throw UnexpectedServerTermination | otherwise = throw e -type RequestMap = IxMap LspId (SMethod :: Method FromClient Request -> Type ) +type RequestMap = IxMap LspId (SMethod :: Method ClientToServer Request -> Type ) newRequestMap :: RequestMap newRequestMap = emptyIxMap diff --git a/lsp-test/src/Language/LSP/Test/Exceptions.hs b/lsp-test/src/Language/LSP/Test/Exceptions.hs index de88a0898..c0b5df63c 100644 --- a/lsp-test/src/Language/LSP/Test/Exceptions.hs +++ b/lsp-test/src/Language/LSP/Test/Exceptions.hs @@ -16,7 +16,7 @@ data SessionException = Timeout (Maybe FromServerMessage) | ReplayOutOfOrder FromServerMessage [FromServerMessage] | UnexpectedDiagnostics | IncorrectApplyEditRequest String - | UnexpectedResponseError SomeLspId ResponseError + | UnexpectedResponseError SomeLspId ResponseError | UnexpectedServerTermination | IllegalInitSequenceMessage FromServerMessage | MessageSendError Value IOError diff --git a/lsp-test/src/Language/LSP/Test/Files.hs b/lsp-test/src/Language/LSP/Test/Files.hs index d27511264..bcc2f08f6 100644 --- a/lsp-test/src/Language/LSP/Test/Files.hs +++ b/lsp-test/src/Language/LSP/Test/Files.hs @@ -10,10 +10,9 @@ module Language.LSP.Test.Files ) where -import Language.LSP.Types -import Language.LSP.Types.Lens hiding (id) +import Language.LSP.Types hiding (error, id) import Control.Lens -import qualified Data.HashMap.Strict as HM +import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Maybe import System.Directory @@ -38,9 +37,11 @@ swapFiles relCurBaseDir msgs = do return newMsgs rootDir :: [Event] -> FilePath -rootDir (ClientEv _ (FromClientMess SInitialize req):_) = +rootDir (ClientEv _ (FromClientMess SMethod_Initialize req):_) = fromMaybe (error "Couldn't find root dir") $ do - rootUri <- req ^. params .rootUri + rootUri <- case req ^. params . rootUri of + InL r -> Just r + InR _ -> error "Couldn't find root dir" uriToFilePath rootUri rootDir _ = error "Couldn't find initialize request in session" @@ -52,25 +53,26 @@ mapUris f event = where --TODO: Handle all other URIs that might need swapped - fromClientMsg (FromClientMess m@SInitialize r) = FromClientMess m $ params .~ transformInit (r ^. params) $ r - fromClientMsg (FromClientMess m@STextDocumentDidOpen n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentDidChange n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentWillSave n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentDidSave n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentDidClose n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentDocumentSymbol n) = FromClientMess m $ swapUri (params . textDocument) n - fromClientMsg (FromClientMess m@STextDocumentRename n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_Initialize r) = FromClientMess m $ params .~ transformInit (r ^. params) $ r + fromClientMsg (FromClientMess m@SMethod_TextDocumentDidOpen n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentDidChange n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentWillSave n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentDidSave n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentDidClose n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentDocumentSymbol n) = FromClientMess m $ swapUri (params . textDocument) n + fromClientMsg (FromClientMess m@SMethod_TextDocumentRename n) = FromClientMess m $ swapUri (params . textDocument) n fromClientMsg x = x fromServerMsg :: FromServerMessage -> FromServerMessage - fromServerMsg (FromServerMess m@SWorkspaceApplyEdit r) = FromServerMess m $ params . edit .~ swapWorkspaceEdit (r ^. params . edit) $ r - fromServerMsg (FromServerMess m@STextDocumentPublishDiagnostics n) = FromServerMess m $ swapUri params n - fromServerMsg (FromServerRsp m@STextDocumentDocumentSymbol r) = - let swapUri' :: (List DocumentSymbol |? List SymbolInformation) -> List DocumentSymbol |? List SymbolInformation - swapUri' (InR si) = InR (swapUri location <$> si) - swapUri' (InL dss) = InL dss -- no file locations here - in FromServerRsp m $ r & result %~ (fmap swapUri') - fromServerMsg (FromServerRsp m@STextDocumentRename r) = FromServerRsp m $ r & result %~ (fmap swapWorkspaceEdit) + fromServerMsg (FromServerMess m@SMethod_WorkspaceApplyEdit r) = FromServerMess m $ params . edit .~ swapWorkspaceEdit (r ^. params . edit) $ r + fromServerMsg (FromServerMess m@SMethod_TextDocumentPublishDiagnostics n) = FromServerMess m $ swapUri params n + fromServerMsg (FromServerRsp m@SMethod_TextDocumentDocumentSymbol r) = + let swapUri' :: ([SymbolInformation] |? [DocumentSymbol] |? Null) -> [SymbolInformation] |? [DocumentSymbol] |? Null + swapUri' (InR (InL dss)) = InR $ InL dss -- no file locations here + swapUri' (InR (InR n)) = InR $ InR n + swapUri' (InL si) = InL (swapUri location <$> si) + in FromServerRsp m $ r & result . _Right %~ swapUri' + fromServerMsg (FromServerRsp m@SMethod_TextDocumentRename r) = FromServerRsp m $ r & result . _Right . _L %~ swapWorkspaceEdit fromServerMsg x = x swapWorkspaceEdit :: WorkspaceEdit -> WorkspaceEdit @@ -81,13 +83,11 @@ mapUris f event = -- for RenameFile, we swap `newUri` swapDocumentChangeUri (InR (InR (InL renameFile))) = InR $ InR $ InL $ newUri .~ f (renameFile ^. newUri) $ renameFile swapDocumentChangeUri (InR (InR (InR deleteFile))) = InR $ InR $ InR $ swapUri id deleteFile + in e & changes . _Just %~ swapKeys f + & documentChanges . _Just . traversed%~ swapDocumentChangeUri - newDocChanges = fmap (fmap swapDocumentChangeUri) $ e ^. documentChanges - newChanges = fmap (swapKeys f) $ e ^. changes - in WorkspaceEdit newChanges newDocChanges Nothing - - swapKeys :: (Uri -> Uri) -> HM.HashMap Uri b -> HM.HashMap Uri b - swapKeys f = HM.foldlWithKey' (\acc k v -> HM.insert (f k) v acc) HM.empty + swapKeys :: (Uri -> Uri) -> M.Map Uri b -> M.Map Uri b + swapKeys f = M.foldlWithKey' (\acc k v -> M.insert (f k) v acc) M.empty swapUri :: HasUri b Uri => Lens' a b -> a -> a swapUri lens x = @@ -97,9 +97,11 @@ mapUris f event = -- | Transforms rootUri/rootPath. transformInit :: InitializeParams -> InitializeParams transformInit x = - let newRootUri = fmap f (x ^. rootUri) - newRootPath = do - fp <- T.unpack <$> x ^. rootPath - let uri = filePathToUri fp - T.pack <$> uriToFilePath (f uri) - in (rootUri .~ newRootUri) $ (rootPath .~ newRootPath) x + let modifyRootPath p = + let fp = T.unpack p + uri = filePathToUri fp + in case uriToFilePath (f uri) of + Just fp -> T.pack fp + Nothing -> p + in x & rootUri . _L %~ f + & rootPath . _Just . _L %~ modifyRootPath diff --git a/lsp-test/src/Language/LSP/Test/Parsing.hs b/lsp-test/src/Language/LSP/Test/Parsing.hs index 43ac49fe5..5006299bd 100644 --- a/lsp-test/src/Language/LSP/Test/Parsing.hs +++ b/lsp-test/src/Language/LSP/Test/Parsing.hs @@ -35,8 +35,10 @@ import Data.Conduit.Parser hiding (named) import qualified Data.Conduit.Parser (named) import qualified Data.Text as T import Data.Typeable -import Language.LSP.Types +import Language.LSP.Types hiding (error, message) import Language.LSP.Test.Session +import GHC.TypeLits (KnownSymbol, symbolVal) +import Data.GADT.Compare -- $receiving -- To receive a message, specify the method of the message to expect: @@ -115,8 +117,8 @@ named s (Session x) = Session (Data.Conduit.Parser.named s x) -- | Matches a request or a notification coming from the server. -- Doesn't match Custom Messages -message :: SServerMethod m -> Session (ServerMessage m) -message (SCustomMethod _) = error "message can't be used with CustomMethod, use customRequest or customNotification instead" +message :: SServerMethod m -> Session (TMessage m) +message (SMethod_CustomMethod _) = error "message can't be used with CustomMethod, use customRequest or customNotification instead" message m1 = named (T.pack $ "Request for: " <> show m1) $ satisfyMaybe $ \case FromServerMess m2 msg -> do res <- mEqServer m1 m2 @@ -125,23 +127,31 @@ message m1 = named (T.pack $ "Request for: " <> show m1) $ satisfyMaybe $ \case Left _f -> Nothing _ -> Nothing -customRequest :: T.Text -> Session (ServerMessage (CustomMethod :: Method FromServer Request)) -customRequest m = named m $ satisfyMaybe $ \case - FromServerMess m1 msg -> case splitServerMethod m1 of - IsServerEither -> case msg of - ReqMess _ | m1 == SCustomMethod m -> Just msg +customRequest :: KnownSymbol s => Proxy s -> Session (TMessage (Method_CustomMethod s :: Method ServerToClient Request)) +customRequest p = + let m = T.pack $ symbolVal p + in named m $ satisfyMaybe $ \case + FromServerMess m1 msg -> case splitServerMethod m1 of + IsServerEither -> case msg of + ReqMess _ -> case m1 `geq` SMethod_CustomMethod p of + Just Refl -> Just msg + _ -> Nothing + _ -> Nothing _ -> Nothing _ -> Nothing - _ -> Nothing -customNotification :: T.Text -> Session (ServerMessage (CustomMethod :: Method FromServer Notification)) -customNotification m = named m $ satisfyMaybe $ \case - FromServerMess m1 msg -> case splitServerMethod m1 of - IsServerEither -> case msg of - NotMess _ | m1 == SCustomMethod m -> Just msg +customNotification :: KnownSymbol s => Proxy s -> Session (TMessage (Method_CustomMethod s :: Method ServerToClient Notification)) +customNotification p = + let m = T.pack $ symbolVal p + in named m $ satisfyMaybe $ \case + FromServerMess m1 msg -> case splitServerMethod m1 of + IsServerEither -> case msg of + NotMess _ -> case m1 `geq` SMethod_CustomMethod p of + Just Refl -> Just msg + _ -> Nothing + _ -> Nothing _ -> Nothing _ -> Nothing - _ -> Nothing -- | Matches if the message is a notification. anyNotification :: Session FromServerMessage @@ -169,7 +179,7 @@ anyResponse = named "Any response" $ satisfy $ \case FromServerRsp _ _ -> True -- | Matches a response coming from the server. -response :: SMethod (m :: Method FromClient Request) -> Session (ResponseMessage m) +response :: SMethod (m :: Method ClientToServer Request) -> Session (TResponseMessage m) response m1 = named (T.pack $ "Response for: " <> show m1) $ satisfyMaybe $ \case FromServerRsp m2 msg -> do HRefl <- runEq mEqClient m1 m2 @@ -177,12 +187,12 @@ response m1 = named (T.pack $ "Response for: " <> show m1) $ satisfyMaybe $ \cas _ -> Nothing -- | Like 'response', but matches a response for a specific id. -responseForId :: SMethod (m :: Method FromClient Request) -> LspId m -> Session (ResponseMessage m) +responseForId :: SMethod (m :: Method ClientToServer Request) -> LspId m -> Session (TResponseMessage m) responseForId m lid = named (T.pack $ "Response for id: " ++ show lid) $ do satisfyMaybe $ \msg -> do case msg of FromServerMess _ _ -> Nothing - FromServerRsp m' rspMsg@(ResponseMessage _ lid' _) -> do + FromServerRsp m' rspMsg@(TResponseMessage _ lid' _) -> do HRefl <- runEq mEqClient m m' guard (Just lid == lid') pure rspMsg @@ -195,16 +205,16 @@ anyMessage = satisfy (const True) loggingNotification :: Session FromServerMessage loggingNotification = named "Logging notification" $ satisfy shouldSkip where - shouldSkip (FromServerMess SWindowLogMessage _) = True - shouldSkip (FromServerMess SWindowShowMessage _) = True - shouldSkip (FromServerMess SWindowShowMessageRequest _) = True - shouldSkip (FromServerMess SWindowShowDocument _) = True + shouldSkip (FromServerMess SMethod_WindowLogMessage _) = True + shouldSkip (FromServerMess SMethod_WindowShowMessage _) = True + shouldSkip (FromServerMess SMethod_WindowShowMessageRequest _) = True + shouldSkip (FromServerMess SMethod_WindowShowDocument _) = True shouldSkip _ = False -- | Matches a 'Language.LSP.Types.TextDocumentPublishDiagnostics' -- (textDocument/publishDiagnostics) notification. -publishDiagnosticsNotification :: Session (Message TextDocumentPublishDiagnostics) +publishDiagnosticsNotification :: Session (TMessage Method_TextDocumentPublishDiagnostics) publishDiagnosticsNotification = named "Publish diagnostics notification" $ satisfyMaybe $ \msg -> case msg of - FromServerMess STextDocumentPublishDiagnostics diags -> Just diags + FromServerMess SMethod_TextDocumentPublishDiagnostics diags -> Just diags _ -> Nothing diff --git a/lsp-test/src/Language/LSP/Test/Session.hs b/lsp-test/src/Language/LSP/Test/Session.hs index 27724a6e8..b51553860 100644 --- a/lsp-test/src/Language/LSP/Test/Session.hs +++ b/lsp-test/src/Language/LSP/Test/Session.hs @@ -5,6 +5,7 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeOperators #-} @@ -52,7 +53,7 @@ import qualified Control.Monad.Trans.Reader as Reader (ask) import Control.Monad.Trans.State (StateT, runStateT, execState) import qualified Control.Monad.Trans.State as State import qualified Data.ByteString.Lazy.Char8 as B -import Data.Aeson hiding (Error) +import Data.Aeson hiding (Error, Null) import Data.Aeson.Encode.Pretty import Data.Conduit as Conduit import Data.Conduit.Parser as Parser @@ -67,9 +68,7 @@ import qualified Data.HashMap.Strict as HashMap import Data.Maybe import Data.Function import Language.LSP.Types.Capabilities -import Language.LSP.Types -import Language.LSP.Types.Lens -import qualified Language.LSP.Types.Lens as LSP +import Language.LSP.Types as LSP hiding (error, to) import Language.LSP.VFS import Language.LSP.Test.Compat import Language.LSP.Test.Decoding @@ -84,6 +83,7 @@ import System.Process (waitForProcess) import System.Timeout ( timeout ) import Data.IORef import Colog.Core (LogAction (..), WithSeverity (..), Severity (..)) +import Data.Row -- | A session representing one instance of launching and connecting to a server. -- @@ -142,7 +142,7 @@ data SessionContext = SessionContext -- Keep curTimeoutId in SessionContext, as its tied to messageChan , curTimeoutId :: IORef Int -- ^ The current timeout we are waiting on , requestMap :: MVar RequestMap - , initRsp :: MVar (ResponseMessage Initialize) + , initRsp :: MVar (TResponseMessage Method_Initialize) , config :: SessionConfig , sessionCapabilities :: ClientCapabilities } @@ -231,9 +231,9 @@ runSessionMonad context state (Session session) = runReaderT (runStateT conduit yield msg chanSource - isLogNotification (ServerMessage (FromServerMess SWindowShowMessage _)) = True - isLogNotification (ServerMessage (FromServerMess SWindowLogMessage _)) = True - isLogNotification (ServerMessage (FromServerMess SWindowShowDocument _)) = True + isLogNotification (ServerMessage (FromServerMess SMethod_WindowShowMessage _)) = True + isLogNotification (ServerMessage (FromServerMess SMethod_WindowLogMessage _)) = True + isLogNotification (ServerMessage (FromServerMess SMethod_WindowShowDocument _)) = True isLogNotification _ = False watchdog :: ConduitM SessionMessage FromServerMessage (StateT SessionState (ReaderT SessionContext IO)) () @@ -307,10 +307,10 @@ updateStateC = awaitForever $ \msg -> do yield msg where respond :: (MonadIO m, HasReader SessionContext m) => FromServerMessage -> m () - respond (FromServerMess SWindowWorkDoneProgressCreate req) = - sendMessage $ ResponseMessage "2.0" (Just $ req ^. LSP.id) (Right Empty) - respond (FromServerMess SWorkspaceApplyEdit r) = do - sendMessage $ ResponseMessage "2.0" (Just $ r ^. LSP.id) (Right $ ApplyWorkspaceEditResponseBody True Nothing Nothing) + respond (FromServerMess SMethod_WindowWorkDoneProgressCreate req) = + sendMessage $ TResponseMessage "2.0" (Just $ req ^. LSP.id) (Right Null) + respond (FromServerMess SMethod_WorkspaceApplyEdit r) = do + sendMessage $ TResponseMessage "2.0" (Just $ r ^. LSP.id) (Right $ ApplyWorkspaceEditResult True Nothing Nothing) respond _ = pure () @@ -324,47 +324,50 @@ documentChangeUri (InR (InR (InR x))) = x ^. uri updateState :: (MonadIO m, HasReader SessionContext m, HasState SessionState m) => FromServerMessage -> m () -updateState (FromServerMess SProgress req) = case req ^. params . value of - Begin _ -> +updateState (FromServerMess SMethod_Progress req) = case req ^. params . value of + v | Just _ <- v ^? _workDoneProgressBegin -> modify $ \s -> s { curProgressSessions = Set.insert (req ^. params . token) $ curProgressSessions s } - End _ -> + v | Just _ <- v ^? _workDoneProgressEnd -> modify $ \s -> s { curProgressSessions = Set.delete (req ^. params . token) $ curProgressSessions s } _ -> pure () -- Keep track of dynamic capability registration -updateState (FromServerMess SClientRegisterCapability req) = do - let List newRegs = (\sr@(SomeRegistration r) -> (r ^. LSP.id, sr)) <$> req ^. params . registrations +updateState (FromServerMess SMethod_ClientRegisterCapability req) = do + let + regs :: [SomeRegistration] + regs = req ^.. params . registrations . traversed . to toSomeRegistration . _Just + let newRegs = (\sr@(SomeRegistration r) -> (r ^. LSP.id, sr)) <$> regs modify $ \s -> s { curDynCaps = Map.union (Map.fromList newRegs) (curDynCaps s) } -updateState (FromServerMess SClientUnregisterCapability req) = do - let List unRegs = (^. LSP.id) <$> req ^. params . unregisterations +updateState (FromServerMess SMethod_ClientUnregisterCapability req) = do + let unRegs = (^. LSP.id) <$> req ^. params . unregisterations 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 +updateState (FromServerMess SMethod_TextDocumentPublishDiagnostics n) = do + let 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 +updateState (FromServerMess SMethod_WorkspaceApplyEdit r) = do -- First, prefer the versioned documentChanges field allChangeParams <- case r ^. params . edit . documentChanges of - Just (List cs) -> do + Just (cs) -> do mapM_ (checkIfNeedsOpened . documentChangeUri) cs -- replace the user provided version numbers with the VFS ones + 1 -- (technically we should check that the user versions match the VFS ones) - cs' <- traverseOf (traverse . _InL . textDocument) bumpNewestVersion cs + cs' <- traverseOf (traverse . _L . textDocument . _versionedTextDocumentIdentifier) bumpNewestVersion cs return $ mapMaybe getParamsFromDocumentChange 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) + mapM_ checkIfNeedsOpened (Map.keys cs) + concat <$> mapM (uncurry getChangeParams) (Map.toList cs) Nothing -> error "WorkspaceEdit contains neither documentChanges nor changes!" @@ -376,7 +379,7 @@ updateState (FromServerMess SWorkspaceApplyEdit r) = do mergedParams = map mergeParams groupedParams -- TODO: Don't do this when replaying a session - forM_ mergedParams (sendMessage . NotificationMessage "2.0" STextDocumentDidChange) + forM_ mergedParams (sendMessage . TNotificationMessage "2.0" SMethod_TextDocumentDidChange) -- Update VFS to new document versions let sortedVersions = map (sortBy (compare `on` (^. textDocument . version))) groupedParams @@ -385,7 +388,7 @@ updateState (FromServerMess SWorkspaceApplyEdit r) = do forM_ latestVersions $ \(VersionedTextDocumentIdentifier uri v) -> modify $ \s -> let oldVFS = vfs s - update (VirtualFile oldV file_ver t) = VirtualFile (fromMaybe oldV v) (file_ver +1) t + update (VirtualFile _ file_ver t) = VirtualFile v (file_ver +1) t newVFS = oldVFS & vfsMap . ix (toNormalizedUri uri) %~ update in s { vfs = newVFS } @@ -399,23 +402,24 @@ updateState (FromServerMess SWorkspaceApplyEdit r) = 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) + msg = TNotificationMessage "2.0" SMethod_TextDocumentDidOpen (DidOpenTextDocumentParams item) sendMessage msg modifyM $ \s -> do let newVFS = flip execState (vfs s) $ openVFS logger msg return $ s { vfs = newVFS } - getParamsFromTextDocumentEdit :: TextDocumentEdit -> DidChangeTextDocumentParams - getParamsFromTextDocumentEdit (TextDocumentEdit docId (List edits)) = do - DidChangeTextDocumentParams docId (List $ map editToChangeEvent edits) + getParamsFromTextDocumentEdit :: TextDocumentEdit -> Maybe DidChangeTextDocumentParams + getParamsFromTextDocumentEdit (TextDocumentEdit docId edits) = + DidChangeTextDocumentParams <$> docId ^? _versionedTextDocumentIdentifier <*> pure (map editToChangeEvent edits) + -- TODO: move somewhere reusable editToChangeEvent :: TextEdit |? AnnotatedTextEdit -> TextDocumentContentChangeEvent - editToChangeEvent (InR e) = TextDocumentContentChangeEvent (Just $ e ^. range) Nothing (e ^. newText) - editToChangeEvent (InL e) = TextDocumentContentChangeEvent (Just $ e ^. range) Nothing (e ^. newText) + editToChangeEvent (InR e) = TextDocumentContentChangeEvent $ InL $ #range .== (e ^. range) .+ #rangeLength .== Nothing .+ #text .== (e ^. newText) + editToChangeEvent (InL e) = TextDocumentContentChangeEvent $ InL $ #range .== (e ^. range) .+ #rangeLength .== Nothing .+ #text .== (e ^. newText) getParamsFromDocumentChange :: DocumentChange -> Maybe DidChangeTextDocumentParams - getParamsFromDocumentChange (InL textDocumentEdit) = Just $ getParamsFromTextDocumentEdit textDocumentEdit + getParamsFromDocumentChange (InL textDocumentEdit) = getParamsFromTextDocumentEdit textDocumentEdit getParamsFromDocumentChange _ = Nothing bumpNewestVersion (VersionedTextDocumentIdentifier uri _) = @@ -426,18 +430,19 @@ updateState (FromServerMess SWorkspaceApplyEdit r) = do textDocumentVersions uri = do vfs <- vfs <$> get let curVer = fromMaybe 0 $ vfs ^? vfsMap . ix (toNormalizedUri uri) . lsp_version - pure $ map (VersionedTextDocumentIdentifier uri . Just) [curVer + 1..] + pure $ map (VersionedTextDocumentIdentifier uri) [curVer + 1..] textDocumentEdits uri edits = do vers <- textDocumentVersions uri - pure $ map (\(v, e) -> TextDocumentEdit v (List [InL e])) $ zip vers edits + pure $ map (\(v, e) -> TextDocumentEdit (review _versionedTextDocumentIdentifier v) [InL e]) $ zip vers edits - getChangeParams uri (List edits) = do - map <$> pure getParamsFromTextDocumentEdit <*> textDocumentEdits uri (reverse edits) + getChangeParams uri edits = do + edits <- textDocumentEdits uri (reverse edits) + pure $ catMaybes $ map getParamsFromTextDocumentEdit edits mergeParams :: [DidChangeTextDocumentParams] -> DidChangeTextDocumentParams mergeParams params = let events = concat (toList (map (toList . (^. contentChanges)) params)) - in DidChangeTextDocumentParams (head params ^. textDocument) (List events) + in DidChangeTextDocumentParams (head params ^. textDocument) events updateState _ = return () sendMessage :: (MonadIO m, HasReader SessionContext m, ToJSON a) => a -> m () diff --git a/lsp-test/test/DummyServer.hs b/lsp-test/test/DummyServer.hs index 237dddcec..389c66a5f 100644 --- a/lsp-test/test/DummyServer.hs +++ b/lsp-test/test/DummyServer.hs @@ -1,11 +1,13 @@ {-# LANGUAGE TypeInType #-} {-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE TypeApplications #-} module DummyServer where import Control.Monad import Control.Monad.Reader -import Data.Aeson hiding (defaultOptions) -import qualified Data.HashMap.Strict as HM +import Data.Aeson hiding (defaultOptions, Null) +import qualified Data.Map.Strict as M import Data.List (isSuffixOf) import Data.String import UnliftIO.Concurrent @@ -15,8 +17,8 @@ import UnliftIO import System.Directory import System.FilePath import System.Process -import Language.LSP.Types -import Data.Default +import Language.LSP.Types hiding (error, options) +import Data.Proxy withDummyServer :: ((Handle, Handle) -> IO ()) -> IO () withDummyServer f = do @@ -31,7 +33,7 @@ withDummyServer f = do , staticHandlers = handlers , interpretHandler = \env -> Iso (\m -> runLspT env (runReaderT m handlerEnv)) liftIO - , options = defaultOptions {executeCommandCommands = Just ["doAnEdit"]} + , options = defaultOptions {optExecuteCommandCommands = Just ["doAnEdit"]} } bracket @@ -41,53 +43,54 @@ withDummyServer f = do data HandlerEnv = HandlerEnv - { relRegToken :: MVar (RegistrationToken WorkspaceDidChangeWatchedFiles) - , absRegToken :: MVar (RegistrationToken WorkspaceDidChangeWatchedFiles) + { relRegToken :: MVar (RegistrationToken Method_WorkspaceDidChangeWatchedFiles) + , absRegToken :: MVar (RegistrationToken Method_WorkspaceDidChangeWatchedFiles) } handlers :: Handlers (ReaderT HandlerEnv (LspM ())) handlers = mconcat - [ notificationHandler SInitialized $ + [ notificationHandler SMethod_Initialized $ \_noti -> - sendNotification SWindowLogMessage $ - LogMessageParams MtLog "initialized" - , requestHandler STextDocumentHover $ + sendNotification SMethod_WindowLogMessage $ + LogMessageParams MessageType_Log "initialized" + , requestHandler SMethod_TextDocumentHover $ \_req responder -> responder $ Right $ - Just $ - Hover (HoverContents (MarkupContent MkPlainText "hello")) Nothing - , requestHandler STextDocumentDocumentSymbol $ + InL $ + Hover (InL (MarkupContent MarkupKind_PlainText "hello")) Nothing + , requestHandler SMethod_TextDocumentDocumentSymbol $ \_req responder -> responder $ Right $ - InL $ - List - [ DocumentSymbol - "foo" - Nothing - SkObject - Nothing - Nothing - (mkRange 0 0 3 6) - (mkRange 0 0 3 6) - Nothing - ] - , notificationHandler STextDocumentDidOpen $ + InR $ InL + [ DocumentSymbol + "foo" + Nothing + SymbolKind_Object + Nothing + Nothing + (mkRange 0 0 3 6) + (mkRange 0 0 3 6) + Nothing + ] + , notificationHandler SMethod_TextDocumentDidOpen $ \noti -> do - let NotificationMessage _ _ (DidOpenTextDocumentParams doc) = noti + let TNotificationMessage _ _ (DidOpenTextDocumentParams doc) = noti TextDocumentItem uri _ _ _ = doc Just fp = uriToFilePath uri diag = Diagnostic (mkRange 0 0 0 1) - (Just DsWarning) + (Just DiagnosticSeverity_Warning) (Just (InL 42)) + Nothing (Just "dummy-server") "Here's a warning" Nothing Nothing + Nothing withRunInIO $ \runInIO -> do when (".hs" `isSuffixOf` fp) $ @@ -96,39 +99,37 @@ handlers = do threadDelay (2 * 10 ^ 6) runInIO $ - sendNotification STextDocumentPublishDiagnostics $ - PublishDiagnosticsParams uri Nothing (List [diag]) + sendNotification SMethod_TextDocumentPublishDiagnostics $ + PublishDiagnosticsParams uri Nothing [diag] -- also act as a registerer for workspace/didChangeWatchedFiles when (".register" `isSuffixOf` fp) $ do let regOpts = - DidChangeWatchedFilesRegistrationOptions $ - List - [ FileSystemWatcher - "*.watch" - (Just (WatchKind True True True)) - ] + DidChangeWatchedFilesRegistrationOptions + [ FileSystemWatcher + (GlobPattern $ InL $ Pattern "*.watch") + (Just WatchKind_Create) + ] Just token <- runInIO $ - registerCapability SWorkspaceDidChangeWatchedFiles regOpts $ + registerCapability SMethod_WorkspaceDidChangeWatchedFiles regOpts $ \_noti -> - sendNotification SWindowLogMessage $ - LogMessageParams MtLog "got workspace/didChangeWatchedFiles" + sendNotification SMethod_WindowLogMessage $ + LogMessageParams MessageType_Log "got workspace/didChangeWatchedFiles" runInIO $ asks relRegToken >>= \v -> putMVar v token when (".register.abs" `isSuffixOf` fp) $ do curDir <- getCurrentDirectory let regOpts = - DidChangeWatchedFilesRegistrationOptions $ - List - [ FileSystemWatcher - (fromString $ curDir "*.watch") - (Just (WatchKind True True True)) - ] + DidChangeWatchedFilesRegistrationOptions + [ FileSystemWatcher + (GlobPattern $ InL $ Pattern $ fromString $ curDir "*.watch") + (Just WatchKind_Create) + ] Just token <- runInIO $ - registerCapability SWorkspaceDidChangeWatchedFiles regOpts $ + registerCapability SMethod_WorkspaceDidChangeWatchedFiles regOpts $ \_noti -> - sendNotification SWindowLogMessage $ - LogMessageParams MtLog "got workspace/didChangeWatchedFiles" + sendNotification SMethod_WindowLogMessage $ + LogMessageParams MessageType_Log "got workspace/didChangeWatchedFiles" runInIO $ asks absRegToken >>= \v -> putMVar v token -- also act as an unregisterer for workspace/didChangeWatchedFiles when (".unregister" `isSuffixOf` fp) $ @@ -142,56 +143,58 @@ handlers = -- this handler is used by the -- "text document VFS / sends back didChange notifications (documentChanges)" test - , notificationHandler STextDocumentDidChange $ \noti -> do - let NotificationMessage _ _ params = noti - void $ sendNotification (SCustomMethod "custom/textDocument/didChange") (toJSON params) + , notificationHandler SMethod_TextDocumentDidChange $ \noti -> do + let TNotificationMessage _ _ params = noti + void $ sendNotification (SMethod_CustomMethod (Proxy @"custom/textDocument/didChange")) (toJSON params) - , requestHandler SWorkspaceExecuteCommand $ \req resp -> do + , requestHandler SMethod_WorkspaceExecuteCommand $ \req resp -> do case req of - RequestMessage _ _ _ (ExecuteCommandParams Nothing "doAnEdit" (Just (List [val]))) -> do + TRequestMessage _ _ _ (ExecuteCommandParams Nothing "doAnEdit" (Just [val])) -> do let Success docUri = fromJSON val - edit = List [TextEdit (mkRange 0 0 0 5) "howdy"] + edit = [TextEdit (mkRange 0 0 0 5) "howdy"] params = ApplyWorkspaceEditParams (Just "Howdy edit") $ - WorkspaceEdit (Just (HM.singleton docUri edit)) Nothing Nothing - resp $ Right Null - void $ sendRequest SWorkspaceApplyEdit params (const (pure ())) - RequestMessage _ _ _ (ExecuteCommandParams Nothing "doAVersionedEdit" (Just (List [val]))) -> do + WorkspaceEdit (Just (M.singleton docUri edit)) Nothing Nothing + resp $ Right $ InR $ Null + void $ sendRequest SMethod_WorkspaceApplyEdit params (const (pure ())) + TRequestMessage _ _ _ (ExecuteCommandParams Nothing "doAVersionedEdit" (Just [val])) -> do let Success versionedDocUri = fromJSON val - edit = List [InL (TextEdit (mkRange 0 0 0 5) "howdy")] + edit = [InL (TextEdit (mkRange 0 0 0 5) "howdy")] documentEdit = TextDocumentEdit versionedDocUri edit params = ApplyWorkspaceEditParams (Just "Howdy edit") $ - WorkspaceEdit Nothing (Just (List [InL documentEdit])) Nothing - resp $ Right Null - void $ sendRequest SWorkspaceApplyEdit params (const (pure ())) - RequestMessage _ _ _ (ExecuteCommandParams _ name _) -> + WorkspaceEdit Nothing (Just [InL documentEdit]) Nothing + resp $ Right $ InR Null + void $ sendRequest SMethod_WorkspaceApplyEdit params (const (pure ())) + TRequestMessage _ _ _ (ExecuteCommandParams _ name _) -> error $ "unsupported command: " <> show name - , requestHandler STextDocumentCodeAction $ \req resp -> do - let RequestMessage _ _ _ params = req + , requestHandler SMethod_TextDocumentCodeAction $ \req resp -> do + let TRequestMessage _ _ _ params = req CodeActionParams _ _ _ _ cactx = params - CodeActionContext diags _ = cactx + CodeActionContext diags _ _ = cactx codeActions = fmap diag2ca diags diag2ca d = CodeAction "Delete this" Nothing - (Just (List [d])) + (Just [d]) Nothing Nothing Nothing (Just (Command "" "deleteThis" Nothing)) Nothing - resp $ Right $ InR <$> codeActions - , requestHandler STextDocumentCompletion $ \_req resp -> do - let res = CompletionList True (List [item]) + resp $ Right $ InL $ InR <$> codeActions + , requestHandler SMethod_TextDocumentCompletion $ \_req resp -> do + let res = CompletionList True Nothing [item] item = CompletionItem "foo" - (Just CiConstant) - (Just (List [])) + Nothing + (Just CompletionItemKind_Constant) + (Just []) + Nothing Nothing Nothing Nothing @@ -206,15 +209,15 @@ handlers = Nothing Nothing Nothing - resp $ Right $ InR res - , requestHandler STextDocumentPrepareCallHierarchy $ \req resp -> do - let RequestMessage _ _ _ params = req + resp $ Right $ InR $ InL res + , requestHandler SMethod_TextDocumentPrepareCallHierarchy $ \req resp -> do + let TRequestMessage _ _ _ params = req CallHierarchyPrepareParams _ pos _ = params Position x y = pos item = CallHierarchyItem "foo" - SkMethod + SymbolKind_Method Nothing Nothing (Uri "") @@ -222,21 +225,21 @@ handlers = (Range (Position 2 3) (Position 4 5)) Nothing if x == 0 && y == 0 - then resp $ Right Nothing - else resp $ Right $ Just $ List [item] - , requestHandler SCallHierarchyIncomingCalls $ \req resp -> do - let RequestMessage _ _ _ params = req + then resp $ Right $ InR Null + else resp $ Right $ InL [item] + , requestHandler SMethod_CallHierarchyIncomingCalls $ \req resp -> do + let TRequestMessage _ _ _ params = req CallHierarchyIncomingCallsParams _ _ item = params - resp $ Right $ Just $ - List [CallHierarchyIncomingCall item (List [Range (Position 2 3) (Position 4 5)])] - , requestHandler SCallHierarchyOutgoingCalls $ \req resp -> do - let RequestMessage _ _ _ params = req + resp $ Right $ InL + [CallHierarchyIncomingCall item [Range (Position 2 3) (Position 4 5)]] + , requestHandler SMethod_CallHierarchyOutgoingCalls $ \req resp -> do + let TRequestMessage _ _ _ params = req CallHierarchyOutgoingCallsParams _ _ item = params - resp $ Right $ Just $ - List [CallHierarchyOutgoingCall item (List [Range (Position 4 5) (Position 2 3)])] - , requestHandler STextDocumentSemanticTokensFull $ \_req resp -> do - let tokens = makeSemanticTokens def [SemanticTokenAbsolute 0 1 2 SttType []] + resp $ Right $ InL + [CallHierarchyOutgoingCall item [Range (Position 4 5) (Position 2 3)]] + , requestHandler SMethod_TextDocumentSemanticTokensFull $ \_req resp -> do + let tokens = makeSemanticTokens defaultSemanticTokensLegend [SemanticTokenAbsolute 0 1 2 SemanticTokenTypes_Type []] case tokens of - Left t -> resp $ Left $ ResponseError InternalError t Nothing - Right tokens -> resp $ Right $ Just tokens + Left t -> resp $ Left $ TResponseError ErrorCodes_InternalError t Nothing + Right tokens -> resp $ Right $ InL tokens ] diff --git a/lsp-test/test/Test.hs b/lsp-test/test/Test.hs index d991aa1d0..102eaaef1 100644 --- a/lsp-test/test/Test.hs +++ b/lsp-test/test/Test.hs @@ -5,27 +5,26 @@ {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE TypeApplications #-} import DummyServer import Test.Hspec import Data.Aeson import Data.Default -import qualified Data.HashMap.Strict as HM +import qualified Data.Map.Strict as M import Data.Either import Data.Maybe import qualified Data.Text as T import Data.Type.Equality +import Data.Proxy import Control.Applicative.Combinators import Control.Concurrent import Control.Monad.IO.Class import Control.Monad import Control.Lens hiding (List, Iso) import Language.LSP.Test -import Language.LSP.Types -import Language.LSP.Types.Lens hiding - (capabilities, message, rename, applyEdit) -import qualified Language.LSP.Types.Lens as LSP -import Language.LSP.Types.Capabilities as LSP +import Language.LSP.Types hiding (message, applyEdit) +import qualified Language.LSP.Types as LSP import System.Directory import System.FilePath import System.Timeout @@ -47,7 +46,7 @@ main = hspec $ around withDummyServer $ do liftIO $ rsp ^. result `shouldSatisfy` isRight it "runSessionWithConfig" $ \(hin, hout) -> - runSessionWithHandles hin hout def didChangeCaps "." $ return () + runSessionWithHandles hin hout def fullCaps "." $ return () describe "withTimeout" $ do it "times out" $ \(hin, hout) -> @@ -56,7 +55,7 @@ main = hspec $ around withDummyServer $ do -- won't receive a request - will timeout -- incoming logging requests shouldn't increase the -- timeout - withTimeout 5 $ skipManyTill anyMessage (message SWorkspaceApplyEdit) + withTimeout 5 $ skipManyTill anyMessage (message SMethod_WorkspaceApplyEdit) -- wait just a bit longer than 5 seconds so we have time -- to open the document in timeout 6000000 sesh `shouldThrow` anySessionException @@ -96,7 +95,7 @@ main = hspec $ around withDummyServer $ do withTimeout 10 $ liftIO $ threadDelay 7000000 getDocumentSymbols doc -- should now timeout - skipManyTill anyMessage (message SWorkspaceApplyEdit) + skipManyTill anyMessage (message SMethod_WorkspaceApplyEdit) isTimeout (Timeout _) = True isTimeout _ = False in sesh `shouldThrow` isTimeout @@ -106,7 +105,7 @@ main = hspec $ around withDummyServer $ do it "throw on time out" $ \(hin, hout) -> let sesh = runSessionWithHandles hin hout (def {messageTimeout = 10}) fullCaps "." $ do skipMany loggingNotification - _ <- message SWorkspaceApplyEdit + _ <- message SMethod_WorkspaceApplyEdit return () in sesh `shouldThrow` anySessionException @@ -119,17 +118,17 @@ main = hspec $ around withDummyServer $ do describe "UnexpectedMessageException" $ do it "throws when there's an unexpected message" $ \(hin, hout) -> - let selector (UnexpectedMessage "Publish diagnostics notification" (FromServerMess SWindowLogMessage _)) = True + let selector (UnexpectedMessage "Publish diagnostics notification" (FromServerMess SMethod_WindowLogMessage _)) = True selector _ = False in runSessionWithHandles hin hout def fullCaps "." publishDiagnosticsNotification `shouldThrow` selector it "provides the correct types that were expected and received" $ \(hin, hout) -> - let selector (UnexpectedMessage "Response for: STextDocumentRename" (FromServerRsp STextDocumentDocumentSymbol _)) = True + let selector (UnexpectedMessage "Response for: STextDocumentRename" (FromServerRsp SMethod_TextDocumentDocumentSymbol _)) = True selector _ = False sesh = do doc <- openDoc "test/data/renamePass/Desktop/simple.hs" "haskell" - sendRequest STextDocumentDocumentSymbol (DocumentSymbolParams Nothing Nothing doc) + sendRequest SMethod_TextDocumentDocumentSymbol (DocumentSymbolParams Nothing Nothing doc) skipMany anyNotification - response STextDocumentRename -- the wrong type + response SMethod_TextDocumentRename -- the wrong type in runSessionWithHandles hin hout def fullCaps "." sesh `shouldThrow` selector @@ -140,19 +139,19 @@ main = hspec $ around withDummyServer $ do VersionedTextDocumentIdentifier _ beforeVersion <- getVersionedDoc doc let args = toJSON (VersionedTextDocumentIdentifier (doc ^. uri) beforeVersion) - reqParams = ExecuteCommandParams Nothing "doAVersionedEdit" (Just (List [args])) + reqParams = ExecuteCommandParams Nothing "doAVersionedEdit" (Just [args]) - request_ SWorkspaceExecuteCommand reqParams + request_ SMethod_WorkspaceExecuteCommand reqParams - editReq <- message SWorkspaceApplyEdit + editReq <- message SMethod_WorkspaceApplyEdit liftIO $ do - let Just (List [InL(TextDocumentEdit vdoc (List [InL edit_]))]) = + let Just [InL(TextDocumentEdit vdoc [InL edit_])] = editReq ^. params . edit . documentChanges - vdoc `shouldBe` VersionedTextDocumentIdentifier (doc ^. uri) beforeVersion + vdoc `shouldBe` OptionalVersionedTextDocumentIdentifier (doc ^. uri) (InL beforeVersion) edit_ `shouldBe` TextEdit (Range (Position 0 0) (Position 0 5)) "howdy" - change <- customNotification "custom/textDocument/didChange" - let NotMess (NotificationMessage _ _ (c::Value)) = change + change <- customNotification (Proxy @"custom/textDocument/didChange") + let NotMess (TNotificationMessage _ _ (c::Value)) = change Success (DidChangeTextDocumentParams reportedVDoc _edit) = fromJSON c VersionedTextDocumentIdentifier _ reportedVersion = reportedVDoc @@ -169,13 +168,13 @@ main = hspec $ around withDummyServer $ do doc <- openDoc "test/data/refactor/Main.hs" "haskell" let args = toJSON (doc ^. uri) - reqParams = ExecuteCommandParams Nothing "doAnEdit" (Just (List [args])) - request_ SWorkspaceExecuteCommand reqParams + reqParams = ExecuteCommandParams Nothing "doAnEdit" (Just [args]) + request_ SMethod_WorkspaceExecuteCommand reqParams - editReq <- message SWorkspaceApplyEdit + editReq <- message SMethod_WorkspaceApplyEdit liftIO $ do let (Just cs) = editReq ^. params . edit . changes - [(u, List es)] = HM.toList cs + [(u, es)] = M.toList cs u `shouldBe` doc ^. uri es `shouldBe` [TextEdit (Range (Position 0 0) (Position 0 5)) "howdy"] contents <- documentContents doc @@ -187,8 +186,8 @@ main = hspec $ around withDummyServer $ do doc <- openDoc "test/data/refactor/Main.hs" "haskell" let args = toJSON (doc ^. uri) - reqParams = ExecuteCommandParams Nothing "doAnEdit" (Just (List [args])) - request_ SWorkspaceExecuteCommand reqParams + reqParams = ExecuteCommandParams Nothing "doAnEdit" (Just [args]) + request_ SMethod_WorkspaceExecuteCommand reqParams contents <- getDocumentEdit doc liftIO $ contents `shouldBe` "howdy:: IO Int\nmain = return (42)\n" @@ -217,19 +216,19 @@ main = hspec $ around withDummyServer $ do skipMany loggingNotification - Left (mainSymbol:_) <- getDocumentSymbols doc + Right (mainSymbol:_) <- getDocumentSymbols doc liftIO $ do mainSymbol ^. name `shouldBe` "foo" - mainSymbol ^. kind `shouldBe` SkObject + mainSymbol ^. kind `shouldBe` SymbolKind_Object mainSymbol ^. range `shouldBe` mkRange 0 0 3 6 describe "applyEdit" $ do - it "increments the version" $ \(hin, hout) -> runSessionWithHandles hin hout def docChangesCaps "." $ do + it "increments the version" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do doc <- openDoc "test/data/renamePass/Desktop/simple.hs" "haskell" - VersionedTextDocumentIdentifier _ (Just oldVersion) <- getVersionedDoc doc + VersionedTextDocumentIdentifier _ oldVersion <- getVersionedDoc doc let edit = TextEdit (Range (Position 1 1) (Position 1 3)) "foo" - VersionedTextDocumentIdentifier _ (Just newVersion) <- applyEdit doc edit + VersionedTextDocumentIdentifier _ newVersion <- applyEdit doc edit liftIO $ newVersion `shouldBe` oldVersion + 1 it "changes the document contents" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do doc <- openDoc "test/data/renamePass/Desktop/simple.hs" "haskell" @@ -277,7 +276,7 @@ main = hspec $ around withDummyServer $ do openDoc "test/data/Error.hs" "haskell" [diag] <- waitForDiagnosticsSource "dummy-server" liftIO $ do - diag ^. severity `shouldBe` Just DsWarning + diag ^. severity `shouldBe` Just DiagnosticSeverity_Warning diag ^. source `shouldBe` Just "dummy-server" -- describe "rename" $ do @@ -328,24 +327,24 @@ main = hspec $ around withDummyServer $ do describe "satisfy" $ it "works" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do openDoc "test/data/Format.hs" "haskell" - let pred (FromServerMess SWindowLogMessage _) = True + let pred (FromServerMess SMethod_WindowLogMessage _) = True pred _ = False void $ satisfy pred describe "satisfyMaybe" $ do it "returns matched data on match" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do -- Wait for window/logMessage "initialized" from the server. - let pred (FromServerMess SWindowLogMessage _) = Just "match" :: Maybe String + let pred (FromServerMess SMethod_WindowLogMessage _) = Just "match" :: Maybe String pred _ = Nothing :: Maybe String result <- satisfyMaybe pred liftIO $ result `shouldBe` "match" it "doesn't return if no match" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do - let pred (FromServerMess STextDocumentPublishDiagnostics _) = Just "matched" :: Maybe String + let pred (FromServerMess SMethod_TextDocumentPublishDiagnostics _) = Just "matched" :: Maybe String pred _ = Nothing :: Maybe String -- We expect a window/logMessage from the server, but -- not a textDocument/publishDiagnostics. - result <- satisfyMaybe pred <|> (message SWindowLogMessage *> pure "no match") + result <- satisfyMaybe pred <|> (message SMethod_WindowLogMessage *> pure "no match") liftIO $ result `shouldBe` "no match" describe "ignoreLogNotifications" $ @@ -360,26 +359,26 @@ main = hspec $ around withDummyServer $ do loggingNotification -- initialized log message createDoc ".register" "haskell" "" - message SClientRegisterCapability + message SMethod_ClientRegisterCapability doc <- createDoc "Foo.watch" "haskell" "" - msg <- message SWindowLogMessage + msg <- message SMethod_WindowLogMessage liftIO $ msg ^. params . LSP.message `shouldBe` "got workspace/didChangeWatchedFiles" - [SomeRegistration (Registration _ regMethod regOpts)] <- getRegisteredCapabilities + [SomeRegistration (TRegistration _ regMethod regOpts)] <- getRegisteredCapabilities liftIO $ do - case regMethod `mEqClient` SWorkspaceDidChangeWatchedFiles of + case regMethod `mEqClient` SMethod_WorkspaceDidChangeWatchedFiles of Just (Right HRefl) -> - regOpts `shouldBe` (Just (DidChangeWatchedFilesRegistrationOptions $ List - [ FileSystemWatcher "*.watch" (Just (WatchKind True True True)) ])) + regOpts `shouldBe` (Just $ DidChangeWatchedFilesRegistrationOptions + [ FileSystemWatcher (GlobPattern $ InL $ Pattern "*.watch") (Just WatchKind_Create) ]) _ -> expectationFailure "Registration wasn't on workspace/didChangeWatchedFiles" -- now unregister it by sending a specific createDoc createDoc ".unregister" "haskell" "" - message SClientUnregisterCapability + message SMethod_ClientUnregisterCapability createDoc "Bar.watch" "haskell" "" - void $ sendRequest STextDocumentHover $ HoverParams doc (Position 0 0) Nothing + void $ sendRequest SMethod_TextDocumentHover $ HoverParams doc (Position 0 0) Nothing count 0 $ loggingNotification void $ anyResponse @@ -389,18 +388,18 @@ main = hspec $ around withDummyServer $ do loggingNotification -- initialized log message createDoc ".register.abs" "haskell" "" - message SClientRegisterCapability + message SMethod_ClientRegisterCapability doc <- createDoc (curDir "Foo.watch") "haskell" "" - msg <- message SWindowLogMessage + msg <- message SMethod_WindowLogMessage liftIO $ msg ^. params . LSP.message `shouldBe` "got workspace/didChangeWatchedFiles" -- now unregister it by sending a specific createDoc createDoc ".unregister.abs" "haskell" "" - message SClientUnregisterCapability + message SMethod_ClientUnregisterCapability createDoc (curDir "Bar.watch") "haskell" "" - void $ sendRequest STextDocumentHover $ HoverParams doc (Position 0 0) Nothing + void $ sendRequest SMethod_TextDocumentHover $ HoverParams doc (Position 0 0) Nothing count 0 $ loggingNotification void $ anyResponse @@ -408,7 +407,7 @@ main = hspec $ around withDummyServer $ do let workPos = Position 1 0 notWorkPos = Position 0 0 params pos = CallHierarchyPrepareParams (TextDocumentIdentifier (Uri "")) pos Nothing - item = CallHierarchyItem "foo" SkFunction Nothing Nothing (Uri "") + item = CallHierarchyItem "foo" SymbolKind_Function Nothing Nothing (Uri "") (Range (Position 1 2) (Position 3 4)) (Range (Position 1 2) (Position 3 4)) Nothing @@ -419,26 +418,14 @@ main = hspec $ around withDummyServer $ do rsp <- prepareCallHierarchy (params notWorkPos) liftIO $ rsp `shouldBe` [] it "incoming calls" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do - [CallHierarchyIncomingCall _ (List fromRanges)] <- incomingCalls (CallHierarchyIncomingCallsParams Nothing Nothing item) + [CallHierarchyIncomingCall _ fromRanges] <- incomingCalls (CallHierarchyIncomingCallsParams Nothing Nothing item) liftIO $ head fromRanges `shouldBe` Range (Position 2 3) (Position 4 5) it "outgoing calls" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do - [CallHierarchyOutgoingCall _ (List fromRanges)] <- outgoingCalls (CallHierarchyOutgoingCallsParams Nothing Nothing item) + [CallHierarchyOutgoingCall _ fromRanges] <- outgoingCalls (CallHierarchyOutgoingCallsParams Nothing Nothing item) liftIO $ head fromRanges `shouldBe` Range (Position 4 5) (Position 2 3) describe "semantic tokens" $ do it "full works" $ \(hin, hout) -> runSessionWithHandles hin hout def fullCaps "." $ do let doc = TextDocumentIdentifier (Uri "") - Just toks <- getSemanticTokens doc - liftIO $ toks ^. xdata `shouldBe` List [0,1,2,1,0] - -didChangeCaps :: ClientCapabilities -didChangeCaps = def { _workspace = Just workspaceCaps } - where - workspaceCaps = def { _didChangeConfiguration = Just configCaps } - configCaps = DidChangeConfigurationClientCapabilities (Just True) - -docChangesCaps :: ClientCapabilities -docChangesCaps = def { _workspace = Just workspaceCaps } - where - workspaceCaps = def { _workspaceEdit = Just editCaps } - editCaps = WorkspaceEditClientCapabilities (Just True) Nothing Nothing Nothing Nothing + InL toks <- getSemanticTokens doc + liftIO $ toks ^. data_ `shouldBe` [0,1,2,1,0] diff --git a/lsp-types/lsp-types.cabal b/lsp-types/lsp-types.cabal index a457da8dc..c7e7d514b 100644 --- a/lsp-types/lsp-types.cabal +++ b/lsp-types/lsp-types.cabal @@ -24,58 +24,35 @@ flag force-ospath library exposed-modules: Language.LSP.Types , Language.LSP.Types.Capabilities - , Language.LSP.Types.Lens , Language.LSP.Types.SMethodMap , Data.IxMap - other-modules: Language.LSP.Types.CallHierarchy - , Language.LSP.Types.Cancellation - , Language.LSP.Types.ClientCapabilities + other-modules: + Language.LSP.Types.Internal.Generated + , Language.LSP.Types.Internal.Lenses + , Language.LSP.Types.CodeAction - , Language.LSP.Types.CodeLens - , Language.LSP.Types.Command , Language.LSP.Types.Common - , Language.LSP.Types.Completion - , Language.LSP.Types.Configuration - , Language.LSP.Types.Declaration - , Language.LSP.Types.Definition - , Language.LSP.Types.Diagnostic - , Language.LSP.Types.DocumentColor - , Language.LSP.Types.DocumentFilter - , Language.LSP.Types.DocumentHighlight - , Language.LSP.Types.DocumentLink - , Language.LSP.Types.DocumentSymbol - , Language.LSP.Types.FoldingRange - , Language.LSP.Types.Formatting - , Language.LSP.Types.Hover - , Language.LSP.Types.Implementation - , Language.LSP.Types.Initialize - , Language.LSP.Types.Location , Language.LSP.Types.LspId + , Language.LSP.Types.Location , Language.LSP.Types.MarkupContent , Language.LSP.Types.Method , Language.LSP.Types.Message , Language.LSP.Types.Parsing , Language.LSP.Types.Progress , Language.LSP.Types.Registration - , Language.LSP.Types.References - , Language.LSP.Types.Rename - , Language.LSP.Types.SelectionRange - , Language.LSP.Types.ServerCapabilities , Language.LSP.Types.SemanticTokens - , Language.LSP.Types.SignatureHelp - , Language.LSP.Types.StaticRegistrationOptions - , Language.LSP.Types.TextDocument - , Language.LSP.Types.TypeDefinition , Language.LSP.Types.Uri , Language.LSP.Types.Utils - , Language.LSP.Types.Window - , Language.LSP.Types.WatchedFiles - , Language.LSP.Types.WorkspaceEdit - , Language.LSP.Types.WorkspaceFolders - , Language.LSP.Types.WorkspaceSymbol , Language.LSP.Types.Uri.OsPath + , Language.LSP.Types.WorkspaceEdit + + , Language.LSP.MetaModel.Types + , Language.LSP.MetaModel.CodeGen + + , Language.Haskell.TH.Compat + , Data.Row.Aeson -- other-extensions: - ghc-options: -Wall + ghc-options: -Wall -Wno-unticked-promoted-constructors build-depends: base >= 4.11 && < 5 , aeson >=1.2.2.0 , binary @@ -84,15 +61,18 @@ library , deepseq , Diff >= 0.2 , dlist + , file-embed , hashable , lens >= 4.15.2 , mtl < 2.4 , network-uri >= 2.6 , mod + , row-types , scientific , some , text , template-haskell + , transformers , unordered-containers , exceptions , safe @@ -111,13 +91,13 @@ test-suite lsp-types-test other-modules: Spec CapabilitiesSpec JsonSpec + LocationSpec MethodSpec ServerCapabilitiesSpec SemanticTokensSpec TypesSpec URIFilePathSpec WorkspaceEditSpec - LocationSpec build-depends: base , QuickCheck -- for instance Arbitrary Value @@ -127,6 +107,7 @@ test-suite lsp-types-test , lsp-types , lens >= 4.15.2 , network-uri + , row-types , quickcheck-instances , text , tuple diff --git a/lsp-types/metaModel.json b/lsp-types/metaModel.json new file mode 100644 index 000000000..276a77b72 --- /dev/null +++ b/lsp-types/metaModel.json @@ -0,0 +1,14383 @@ +{ + "metaData": { + "version": "3.17.0" + }, + "requests": [ + { + "method": "textDocument/implementation", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Definition" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "ImplementationParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "ImplementationRegistrationOptions" + }, + "documentation": "A request to resolve the implementation locations of a symbol at a given text\ndocument position. The request's parameter is of type [TextDocumentPositionParams]\n(#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\nThenable that resolves to such." + }, + { + "method": "textDocument/typeDefinition", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Definition" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "TypeDefinitionParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "TypeDefinitionRegistrationOptions" + }, + "documentation": "A request to resolve the type definition locations of a symbol at a given text\ndocument position. The request's parameter is of type [TextDocumentPositionParams]\n(#TextDocumentPositionParams) the response is of type [Definition](#Definition) or a\nThenable that resolves to such." + }, + { + "method": "workspace/workspaceFolders", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceFolder" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "serverToClient", + "documentation": "The `workspace/workspaceFolders` is sent from the server to the client to fetch the open workspace folders." + }, + { + "method": "workspace/configuration", + "result": { + "kind": "array", + "element": { + "kind": "reference", + "name": "LSPAny" + } + }, + "messageDirection": "serverToClient", + "params": { + "kind": "and", + "items": [ + { + "kind": "reference", + "name": "ConfigurationParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ] + }, + "documentation": "The 'workspace/configuration' request is sent from the server to the client to fetch a certain\nconfiguration setting.\n\nThis pull model replaces the old push model were the client signaled configuration change via an\nevent. If the server still needs to react to configuration changes (since the server caches the\nresult of `workspace/configuration` requests) the server should register for an empty configuration\nchange event and empty the cache if such an event is received." + }, + { + "method": "textDocument/documentColor", + "result": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ColorInformation" + } + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentColorParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ColorInformation" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentColorRegistrationOptions" + }, + "documentation": "A request to list all color symbols found in a given text document. The request's\nparameter is of type [DocumentColorParams](#DocumentColorParams) the\nresponse is of type [ColorInformation[]](#ColorInformation) or a Thenable\nthat resolves to such." + }, + { + "method": "textDocument/colorPresentation", + "result": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ColorPresentation" + } + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "ColorPresentationParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ColorPresentation" + } + }, + "registrationOptions": { + "kind": "and", + "items": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + }, + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ] + }, + "documentation": "A request to list all presentation for a color. The request's\nparameter is of type [ColorPresentationParams](#ColorPresentationParams) the\nresponse is of type [ColorInformation[]](#ColorInformation) or a Thenable\nthat resolves to such." + }, + { + "method": "textDocument/foldingRange", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "FoldingRange" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "FoldingRangeParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FoldingRange" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "FoldingRangeRegistrationOptions" + }, + "documentation": "A request to provide folding ranges in a document. The request's\nparameter is of type [FoldingRangeParams](#FoldingRangeParams), the\nresponse is of type [FoldingRangeList](#FoldingRangeList) or a Thenable\nthat resolves to such." + }, + { + "method": "textDocument/declaration", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Declaration" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DeclarationLink" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DeclarationParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DeclarationLink" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "DeclarationRegistrationOptions" + }, + "documentation": "A request to resolve the type definition locations of a symbol at a given text\ndocument position. The request's parameter is of type [TextDocumentPositionParams]\n(#TextDocumentPositionParams) the response is of type [Declaration](#Declaration)\nor a typed array of [DeclarationLink](#DeclarationLink) or a Thenable that resolves\nto such." + }, + { + "method": "textDocument/selectionRange", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "SelectionRange" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SelectionRangeParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SelectionRange" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "SelectionRangeRegistrationOptions" + }, + "documentation": "A request to provide selection ranges in a document. The request's\nparameter is of type [SelectionRangeParams](#SelectionRangeParams), the\nresponse is of type [SelectionRange[]](#SelectionRange[]) or a Thenable\nthat resolves to such." + }, + { + "method": "window/workDoneProgress/create", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "WorkDoneProgressCreateParams" + }, + "documentation": "The `window/workDoneProgress/create` request is sent from the server to the client to initiate progress\nreporting from the server." + }, + { + "method": "textDocument/prepareCallHierarchy", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "CallHierarchyItem" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CallHierarchyPrepareParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "CallHierarchyRegistrationOptions" + }, + "documentation": "A request to result a `CallHierarchyItem` in a document at a given position.\nCan be used as an input to an incoming or outgoing call hierarchy.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "callHierarchy/incomingCalls", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "CallHierarchyIncomingCall" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CallHierarchyIncomingCallsParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CallHierarchyIncomingCall" + } + }, + "documentation": "A request to resolve the incoming calls for a given `CallHierarchyItem`.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "callHierarchy/outgoingCalls", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "CallHierarchyOutgoingCall" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CallHierarchyOutgoingCallsParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CallHierarchyOutgoingCall" + } + }, + "documentation": "A request to resolve the outgoing calls for a given `CallHierarchyItem`.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/semanticTokens/full", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SemanticTokens" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SemanticTokensParams" + }, + "partialResult": { + "kind": "reference", + "name": "SemanticTokensPartialResult" + }, + "registrationMethod": "textDocument/semanticTokens", + "registrationOptions": { + "kind": "reference", + "name": "SemanticTokensRegistrationOptions" + }, + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/semanticTokens/full/delta", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SemanticTokens" + }, + { + "kind": "reference", + "name": "SemanticTokensDelta" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SemanticTokensDeltaParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SemanticTokensPartialResult" + }, + { + "kind": "reference", + "name": "SemanticTokensDeltaPartialResult" + } + ] + }, + "registrationMethod": "textDocument/semanticTokens", + "registrationOptions": { + "kind": "reference", + "name": "SemanticTokensRegistrationOptions" + }, + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/semanticTokens/range", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SemanticTokens" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SemanticTokensRangeParams" + }, + "partialResult": { + "kind": "reference", + "name": "SemanticTokensPartialResult" + }, + "registrationMethod": "textDocument/semanticTokens", + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/semanticTokens/refresh", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "clientToServer", + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "window/showDocument", + "result": { + "kind": "reference", + "name": "ShowDocumentResult" + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "ShowDocumentParams" + }, + "documentation": "A request to show a document. This request might open an\nexternal program depending on the value of the URI to open.\nFor example a request to open `https://code.visualstudio.com/`\nwill very likely open the URI in a WEB browser.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/linkedEditingRange", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "LinkedEditingRanges" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "LinkedEditingRangeParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "LinkedEditingRangeRegistrationOptions" + }, + "documentation": "A request to provide ranges that can be edited together.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/willCreateFiles", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceEdit" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CreateFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The will create files request is sent from the client to the server before files are actually\ncreated as long as the creation is triggered from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/willRenameFiles", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceEdit" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "RenameFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The will rename files request is sent from the client to the server before files are actually\nrenamed as long as the rename is triggered from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/willDeleteFiles", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceEdit" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DeleteFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The did delete files notification is sent from the client to the server when\nfiles were deleted from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/moniker", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Moniker" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "MonikerParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Moniker" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "MonikerRegistrationOptions" + }, + "documentation": "A request to get the moniker of a symbol at a given text document position.\nThe request parameter is of type [TextDocumentPositionParams](#TextDocumentPositionParams).\nThe response is of type [Moniker[]](#Moniker[]) or `null`." + }, + { + "method": "textDocument/prepareTypeHierarchy", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "TypeHierarchyPrepareParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TypeHierarchyRegistrationOptions" + }, + "documentation": "A request to result a `TypeHierarchyItem` in a document at a given position.\nCan be used as an input to a subtypes or supertypes type hierarchy.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "typeHierarchy/supertypes", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "TypeHierarchySupertypesParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + }, + "documentation": "A request to resolve the supertypes for a given `TypeHierarchyItem`.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "typeHierarchy/subtypes", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "TypeHierarchySubtypesParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + }, + "documentation": "A request to resolve the subtypes for a given `TypeHierarchyItem`.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "textDocument/inlineValue", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "InlineValue" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "InlineValueParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "InlineValue" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "InlineValueRegistrationOptions" + }, + "documentation": "A request to provide inline values in a document. The request's parameter is of\ntype [InlineValueParams](#InlineValueParams), the response is of type\n[InlineValue[]](#InlineValue[]) or a Thenable that resolves to such.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "workspace/inlineValue/refresh", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "clientToServer", + "documentation": "@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "textDocument/inlayHint", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "InlayHint" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "InlayHintParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "InlayHint" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "InlayHintRegistrationOptions" + }, + "documentation": "A request to provide inlay hints in a document. The request's parameter is of\ntype [InlayHintsParams](#InlayHintsParams), the response is of type\n[InlayHint[]](#InlayHint[]) or a Thenable that resolves to such.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "inlayHint/resolve", + "result": { + "kind": "reference", + "name": "InlayHint" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "InlayHint" + }, + "documentation": "A request to resolve additional properties for an inlay hint.\nThe request's parameter is of type [InlayHint](#InlayHint), the response is\nof type [InlayHint](#InlayHint) or a Thenable that resolves to such.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "workspace/inlayHint/refresh", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "clientToServer", + "documentation": "@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "textDocument/diagnostic", + "result": { + "kind": "reference", + "name": "DocumentDiagnosticReport" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentDiagnosticParams" + }, + "partialResult": { + "kind": "reference", + "name": "DocumentDiagnosticReportPartialResult" + }, + "errorData": { + "kind": "reference", + "name": "DiagnosticServerCancellationData" + }, + "registrationOptions": { + "kind": "reference", + "name": "DiagnosticRegistrationOptions" + }, + "documentation": "The document diagnostic request definition.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "workspace/diagnostic", + "result": { + "kind": "reference", + "name": "WorkspaceDiagnosticReport" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WorkspaceDiagnosticParams" + }, + "partialResult": { + "kind": "reference", + "name": "WorkspaceDiagnosticReportPartialResult" + }, + "errorData": { + "kind": "reference", + "name": "DiagnosticServerCancellationData" + }, + "documentation": "The workspace diagnostic request definition.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "workspace/diagnostic/refresh", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "clientToServer", + "documentation": "The diagnostic refresh request definition.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "client/registerCapability", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "RegistrationParams" + }, + "documentation": "The `client/registerCapability` request is sent from the server to the client to register a new capability\nhandler on the client side." + }, + { + "method": "client/unregisterCapability", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "UnregistrationParams" + }, + "documentation": "The `client/unregisterCapability` request is sent from the server to the client to unregister a previously registered capability\nhandler on the client side." + }, + { + "method": "initialize", + "result": { + "kind": "reference", + "name": "InitializeResult" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "InitializeParams" + }, + "errorData": { + "kind": "reference", + "name": "InitializeError" + }, + "documentation": "The initialize request is sent from the client to the server.\nIt is sent once as the request after starting up the server.\nThe requests parameter is of type [InitializeParams](#InitializeParams)\nthe response if of type [InitializeResult](#InitializeResult) of a Thenable that\nresolves to such." + }, + { + "method": "shutdown", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "clientToServer", + "documentation": "A shutdown request is sent from the client to the server.\nIt is sent once when the client decides to shutdown the\nserver. The only notification that is sent after a shutdown request\nis the exit event." + }, + { + "method": "window/showMessageRequest", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "MessageActionItem" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "ShowMessageRequestParams" + }, + "documentation": "The show message request is sent from the server to the client to show a message\nand a set of options actions to the user." + }, + { + "method": "textDocument/willSaveWaitUntil", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WillSaveTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + "documentation": "A document will save request is sent from the client to the server before\nthe document is actually saved. The request can return an array of TextEdits\nwhich will be applied to the text document before it is saved. Please note that\nclients might drop results if computing the text edits took too long or if a\nserver constantly fails on this request. This is done to keep the save fast and\nreliable." + }, + { + "method": "textDocument/completion", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItem" + } + }, + { + "kind": "reference", + "name": "CompletionList" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CompletionParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItem" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "CompletionRegistrationOptions" + }, + "documentation": "Request to request completion at a given text document position. The request's\nparameter is of type [TextDocumentPosition](#TextDocumentPosition) the response\nis of type [CompletionItem[]](#CompletionItem) or [CompletionList](#CompletionList)\nor a Thenable that resolves to such.\n\nThe request can delay the computation of the [`detail`](#CompletionItem.detail)\nand [`documentation`](#CompletionItem.documentation) properties to the `completionItem/resolve`\nrequest. However, properties that are needed for the initial sorting and filtering, like `sortText`,\n`filterText`, `insertText`, and `textEdit`, must not be changed during resolve." + }, + { + "method": "completionItem/resolve", + "result": { + "kind": "reference", + "name": "CompletionItem" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CompletionItem" + }, + "documentation": "Request to resolve additional information for a given completion item.The request's\nparameter is of type [CompletionItem](#CompletionItem) the response\nis of type [CompletionItem](#CompletionItem) or a Thenable that resolves to such." + }, + { + "method": "textDocument/hover", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Hover" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "HoverParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "HoverRegistrationOptions" + }, + "documentation": "Request to request hover information at a given text document position. The request's\nparameter is of type [TextDocumentPosition](#TextDocumentPosition) the response is of\ntype [Hover](#Hover) or a Thenable that resolves to such." + }, + { + "method": "textDocument/signatureHelp", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SignatureHelp" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SignatureHelpParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "SignatureHelpRegistrationOptions" + } + }, + { + "method": "textDocument/definition", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Definition" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DefinitionParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DefinitionLink" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "DefinitionRegistrationOptions" + }, + "documentation": "A request to resolve the definition location of a symbol at a given text\ndocument position. The request's parameter is of type [TextDocumentPosition]\n(#TextDocumentPosition) the response is of either type [Definition](#Definition)\nor a typed array of [DefinitionLink](#DefinitionLink) or a Thenable that resolves\nto such." + }, + { + "method": "textDocument/references", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "ReferenceParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "ReferenceRegistrationOptions" + }, + "documentation": "A request to resolve project-wide references for the symbol denoted\nby the given text document position. The request's parameter is of\ntype [ReferenceParams](#ReferenceParams) the response is of type\n[Location[]](#Location) or a Thenable that resolves to such." + }, + { + "method": "textDocument/documentHighlight", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentHighlight" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentHighlightParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentHighlight" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentHighlightRegistrationOptions" + }, + "documentation": "Request to resolve a [DocumentHighlight](#DocumentHighlight) for a given\ntext document position. The request's parameter is of type [TextDocumentPosition]\n(#TextDocumentPosition) the request response is of type [DocumentHighlight[]]\n(#DocumentHighlight) or a Thenable that resolves to such." + }, + { + "method": "textDocument/documentSymbol", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolInformation" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentSymbol" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentSymbolParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolInformation" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentSymbol" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentSymbolRegistrationOptions" + }, + "documentation": "A request to list all symbols found in a given text document. The request's\nparameter is of type [TextDocumentIdentifier](#TextDocumentIdentifier) the\nresponse is of type [SymbolInformation[]](#SymbolInformation) or a Thenable\nthat resolves to such." + }, + { + "method": "textDocument/codeAction", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Command" + }, + { + "kind": "reference", + "name": "CodeAction" + } + ] + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CodeActionParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Command" + }, + { + "kind": "reference", + "name": "CodeAction" + } + ] + } + }, + "registrationOptions": { + "kind": "reference", + "name": "CodeActionRegistrationOptions" + }, + "documentation": "A request to provide commands for the given text document and range." + }, + { + "method": "codeAction/resolve", + "result": { + "kind": "reference", + "name": "CodeAction" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CodeAction" + }, + "documentation": "Request to resolve additional information for a given code action.The request's\nparameter is of type [CodeAction](#CodeAction) the response\nis of type [CodeAction](#CodeAction) or a Thenable that resolves to such." + }, + { + "method": "workspace/symbol", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolInformation" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceSymbol" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WorkspaceSymbolParams" + }, + "partialResult": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolInformation" + } + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceSymbol" + } + } + ] + }, + "registrationOptions": { + "kind": "reference", + "name": "WorkspaceSymbolRegistrationOptions" + }, + "documentation": "A request to list project-wide symbols matching the query string given\nby the [WorkspaceSymbolParams](#WorkspaceSymbolParams). The response is\nof type [SymbolInformation[]](#SymbolInformation) or a Thenable that\nresolves to such.\n\n@since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients\n need to advertise support for WorkspaceSymbols via the client capability\n `workspace.symbol.resolveSupport`.\n", + "since": "3.17.0 - support for WorkspaceSymbol in the returned data. Clients\nneed to advertise support for WorkspaceSymbols via the client capability\n`workspace.symbol.resolveSupport`." + }, + { + "method": "workspaceSymbol/resolve", + "result": { + "kind": "reference", + "name": "WorkspaceSymbol" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WorkspaceSymbol" + }, + "documentation": "A request to resolve the range inside the workspace\nsymbol's location.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "textDocument/codeLens", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "CodeLens" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CodeLensParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CodeLens" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "CodeLensRegistrationOptions" + }, + "documentation": "A request to provide code lens for the given text document." + }, + { + "method": "codeLens/resolve", + "result": { + "kind": "reference", + "name": "CodeLens" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CodeLens" + }, + "documentation": "A request to resolve a command for a given code lens." + }, + { + "method": "workspace/codeLens/refresh", + "result": { + "kind": "base", + "name": "null" + }, + "messageDirection": "serverToClient", + "documentation": "A request to refresh all code actions\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "textDocument/documentLink", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentLink" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentLinkParams" + }, + "partialResult": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentLink" + } + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentLinkRegistrationOptions" + }, + "documentation": "A request to provide document links" + }, + { + "method": "documentLink/resolve", + "result": { + "kind": "reference", + "name": "DocumentLink" + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentLink" + }, + "documentation": "Request to resolve additional information for a given document link. The request's\nparameter is of type [DocumentLink](#DocumentLink) the response\nis of type [DocumentLink](#DocumentLink) or a Thenable that resolves to such." + }, + { + "method": "textDocument/formatting", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentFormattingParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentFormattingRegistrationOptions" + }, + "documentation": "A request to to format a whole document." + }, + { + "method": "textDocument/rangeFormatting", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentRangeFormattingParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentRangeFormattingRegistrationOptions" + }, + "documentation": "A request to to format a range in a document." + }, + { + "method": "textDocument/onTypeFormatting", + "result": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DocumentOnTypeFormattingParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "DocumentOnTypeFormattingRegistrationOptions" + }, + "documentation": "A request to format a document on type." + }, + { + "method": "textDocument/rename", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceEdit" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "RenameParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "RenameRegistrationOptions" + }, + "documentation": "A request to rename a symbol." + }, + { + "method": "textDocument/prepareRename", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "PrepareRenameResult" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "PrepareRenameParams" + }, + "documentation": "A request to test and perform the setup necessary for a rename.\n\n@since 3.16 - support for default behavior", + "since": "3.16 - support for default behavior" + }, + { + "method": "workspace/executeCommand", + "result": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "LSPAny" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "ExecuteCommandParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "ExecuteCommandRegistrationOptions" + }, + "documentation": "A request send from the client to the server to execute a command. The request might return\na workspace edit which the client will apply to the workspace." + }, + { + "method": "workspace/applyEdit", + "result": { + "kind": "reference", + "name": "ApplyWorkspaceEditResult" + }, + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "ApplyWorkspaceEditParams" + }, + "documentation": "A request sent from the server to the client to modified certain resources." + } + ], + "notifications": [ + { + "method": "workspace/didChangeWorkspaceFolders", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidChangeWorkspaceFoldersParams" + }, + "documentation": "The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace\nfolder configuration changes." + }, + { + "method": "window/workDoneProgress/cancel", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WorkDoneProgressCancelParams" + }, + "documentation": "The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress\ninitiated on the server side." + }, + { + "method": "workspace/didCreateFiles", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "CreateFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The did create files notification is sent from the client to the server when\nfiles were created from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/didRenameFiles", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "RenameFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The did rename files notification is sent from the client to the server when\nfiles were renamed from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "workspace/didDeleteFiles", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DeleteFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "documentation": "The will delete files request is sent from the client to the server before files are actually\ndeleted as long as the deletion is triggered from within the client.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "method": "notebookDocument/didOpen", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidOpenNotebookDocumentParams" + }, + "registrationMethod": "notebookDocument/sync", + "documentation": "A notification sent when a notebook opens.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "notebookDocument/didChange", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidChangeNotebookDocumentParams" + }, + "registrationMethod": "notebookDocument/sync" + }, + { + "method": "notebookDocument/didSave", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidSaveNotebookDocumentParams" + }, + "registrationMethod": "notebookDocument/sync", + "documentation": "A notification sent when a notebook document is saved.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "notebookDocument/didClose", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidCloseNotebookDocumentParams" + }, + "registrationMethod": "notebookDocument/sync", + "documentation": "A notification sent when a notebook closes.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "method": "initialized", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "InitializedParams" + }, + "documentation": "The initialized notification is sent from the client to the\nserver after the client is fully initialized and the server\nis allowed to send requests from the server to the client." + }, + { + "method": "exit", + "messageDirection": "clientToServer", + "documentation": "The exit event is sent from the client to the server to\nask the server to exit its process." + }, + { + "method": "workspace/didChangeConfiguration", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidChangeConfigurationParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "DidChangeConfigurationRegistrationOptions" + }, + "documentation": "The configuration change notification is sent from the client to the server\nwhen the client's configuration has changed. The notification contains\nthe changed configuration as defined by the language client." + }, + { + "method": "window/showMessage", + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "ShowMessageParams" + }, + "documentation": "The show message notification is sent from a server to a client to ask\nthe client to display a particular message in the user interface." + }, + { + "method": "window/logMessage", + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "LogMessageParams" + }, + "documentation": "The log message notification is sent from the server to the client to ask\nthe client to log a particular message." + }, + { + "method": "telemetry/event", + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "LSPAny" + }, + "documentation": "The telemetry event notification is sent from the server to the client to ask\nthe client to log telemetry data." + }, + { + "method": "textDocument/didOpen", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidOpenTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + "documentation": "The document open notification is sent from the client to the server to signal\nnewly opened text documents. The document's truth is now managed by the client\nand the server must not try to read the document's truth using the document's\nuri. Open in this sense means it is managed by the client. It doesn't necessarily\nmean that its content is presented in an editor. An open notification must not\nbe sent more than once without a corresponding close notification send before.\nThis means open and close notification must be balanced and the max open count\nis one." + }, + { + "method": "textDocument/didChange", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidChangeTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentChangeRegistrationOptions" + }, + "documentation": "The document change notification is sent from the client to the server to signal\nchanges to a text document." + }, + { + "method": "textDocument/didClose", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidCloseTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + "documentation": "The document close notification is sent from the client to the server when\nthe document got closed in the client. The document's truth now exists where\nthe document's uri points to (e.g. if the document's uri is a file uri the\ntruth now exists on disk). As with the open notification the close notification\nis about managing the document's content. Receiving a close notification\ndoesn't mean that the document was open in an editor before. A close\nnotification requires a previous open notification to be sent." + }, + { + "method": "textDocument/didSave", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidSaveTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentSaveRegistrationOptions" + }, + "documentation": "The document save notification is sent from the client to the server when\nthe document got saved in the client." + }, + { + "method": "textDocument/willSave", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "WillSaveTextDocumentParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + "documentation": "A document will save notification is sent from the client to the server before\nthe document is actually saved." + }, + { + "method": "workspace/didChangeWatchedFiles", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "DidChangeWatchedFilesParams" + }, + "registrationOptions": { + "kind": "reference", + "name": "DidChangeWatchedFilesRegistrationOptions" + }, + "documentation": "The watched files notification is sent from the client to the server when\nthe client detects changes to file watched by the language client." + }, + { + "method": "textDocument/publishDiagnostics", + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "PublishDiagnosticsParams" + }, + "documentation": "Diagnostics notification are sent from the server to the client to signal\nresults of validation runs." + }, + { + "method": "$/setTrace", + "messageDirection": "clientToServer", + "params": { + "kind": "reference", + "name": "SetTraceParams" + } + }, + { + "method": "$/logTrace", + "messageDirection": "serverToClient", + "params": { + "kind": "reference", + "name": "LogTraceParams" + } + }, + { + "method": "$/cancelRequest", + "messageDirection": "both", + "params": { + "kind": "reference", + "name": "CancelParams" + } + }, + { + "method": "$/progress", + "messageDirection": "both", + "params": { + "kind": "reference", + "name": "ProgressParams" + } + } + ], + "structures": [ + { + "name": "ImplementationParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ] + }, + { + "name": "Location", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + } + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + } + } + ], + "documentation": "Represents a location inside a resource, such as a line\ninside a text file." + }, + { + "name": "ImplementationRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "ImplementationOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "TypeDefinitionParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ] + }, + { + "name": "TypeDefinitionRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "TypeDefinitionOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "WorkspaceFolder", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "The associated URI for this workspace folder." + }, + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of the workspace folder. Used to refer to this\nworkspace folder in the user interface." + } + ], + "documentation": "A workspace folder inside a client." + }, + { + "name": "DidChangeWorkspaceFoldersParams", + "properties": [ + { + "name": "event", + "type": { + "kind": "reference", + "name": "WorkspaceFoldersChangeEvent" + }, + "documentation": "The actual workspace folder change event." + } + ], + "documentation": "The parameters of a `workspace/didChangeWorkspaceFolders` notification." + }, + { + "name": "ConfigurationParams", + "properties": [ + { + "name": "items", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ConfigurationItem" + } + } + } + ], + "documentation": "The parameters of a configuration request." + }, + { + "name": "PartialResultParams", + "properties": [ + { + "name": "partialResultToken", + "type": { + "kind": "reference", + "name": "ProgressToken" + }, + "optional": true, + "documentation": "An optional token that a server can use to report partial results (e.g. streaming) to\nthe client." + } + ] + }, + { + "name": "DocumentColorParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [DocumentColorRequest](#DocumentColorRequest)." + }, + { + "name": "ColorInformation", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range in the document where this color appears." + }, + { + "name": "color", + "type": { + "kind": "reference", + "name": "Color" + }, + "documentation": "The actual color value for this color range." + } + ], + "documentation": "Represents a color range from a document." + }, + { + "name": "DocumentColorRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentColorOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "ColorPresentationParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "color", + "type": { + "kind": "reference", + "name": "Color" + }, + "documentation": "The color to request presentations for." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range where the color would be inserted. Serves as a context." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [ColorPresentationRequest](#ColorPresentationRequest)." + }, + { + "name": "ColorPresentation", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The label of this color presentation. It will be shown on the color\npicker header. By default this is also the text that is inserted when selecting\nthis color presentation." + }, + { + "name": "textEdit", + "type": { + "kind": "reference", + "name": "TextEdit" + }, + "optional": true, + "documentation": "An [edit](#TextEdit) which is applied to a document when selecting\nthis presentation for the color. When `falsy` the [label](#ColorPresentation.label)\nis used." + }, + { + "name": "additionalTextEdits", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + "optional": true, + "documentation": "An optional array of additional [text edits](#TextEdit) that are applied when\nselecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves." + } + ] + }, + { + "name": "WorkDoneProgressOptions", + "properties": [ + { + "name": "workDoneProgress", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true + } + ] + }, + { + "name": "TextDocumentRegistrationOptions", + "properties": [ + { + "name": "documentSelector", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "DocumentSelector" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "A document selector to identify the scope of the registration. If set to null\nthe document selector provided on the client side will be used." + } + ], + "documentation": "General text document registration options." + }, + { + "name": "FoldingRangeParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [FoldingRangeRequest](#FoldingRangeRequest)." + }, + { + "name": "FoldingRange", + "properties": [ + { + "name": "startLine", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The zero-based start line of the range to fold. The folded area starts after the line's last character.\nTo be valid, the end must be zero or larger and smaller than the number of lines in the document." + }, + { + "name": "startCharacter", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line." + }, + { + "name": "endLine", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The zero-based end line of the range to fold. The folded area ends with the line's last character.\nTo be valid, the end must be zero or larger and smaller than the number of lines in the document." + }, + { + "name": "endCharacter", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "FoldingRangeKind" + }, + "optional": true, + "documentation": "Describes the kind of the folding range such as `comment' or 'region'. The kind\nis used to categorize folding ranges and used by commands like 'Fold all comments'.\nSee [FoldingRangeKind](#FoldingRangeKind) for an enumeration of standardized kinds." + }, + { + "name": "collapsedText", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The text that the client should show when the specified range is\ncollapsed. If not defined or not supported by the client, a default\nwill be chosen by the client.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Represents a folding range. To be valid, start and end line must be bigger than zero and smaller\nthan the number of lines in the document. Clients are free to ignore invalid ranges." + }, + { + "name": "FoldingRangeRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "FoldingRangeOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "DeclarationParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ] + }, + { + "name": "DeclarationRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "DeclarationOptions" + }, + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "SelectionRangeParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "positions", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Position" + } + }, + "documentation": "The positions inside the text document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "A parameter literal used in selection range requests." + }, + { + "name": "SelectionRange", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The [range](#Range) of this selection range." + }, + { + "name": "parent", + "type": { + "kind": "reference", + "name": "SelectionRange" + }, + "optional": true, + "documentation": "The parent selection range containing this range. Therefore `parent.range` must contain `this.range`." + } + ], + "documentation": "A selection range represents a part of a selection hierarchy. A selection range\nmay have a parent selection range that contains it." + }, + { + "name": "SelectionRangeRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "SelectionRangeOptions" + }, + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "WorkDoneProgressCreateParams", + "properties": [ + { + "name": "token", + "type": { + "kind": "reference", + "name": "ProgressToken" + }, + "documentation": "The token to be used to report progress." + } + ] + }, + { + "name": "WorkDoneProgressCancelParams", + "properties": [ + { + "name": "token", + "type": { + "kind": "reference", + "name": "ProgressToken" + }, + "documentation": "The token to be used to report progress." + } + ] + }, + { + "name": "CallHierarchyPrepareParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameter of a `textDocument/prepareCallHierarchy` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyItem", + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of this item." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "SymbolKind" + }, + "documentation": "The kind of this item." + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "optional": true, + "documentation": "Tags for this item." + }, + { + "name": "detail", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "More detail for this item, e.g. the signature of a function." + }, + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The resource identifier of this item." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code." + }, + { + "name": "selectionRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function.\nMust be contained by the [`range`](#CallHierarchyItem.range)." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved between a call hierarchy prepare and\nincoming calls or outgoing calls requests." + } + ], + "documentation": "Represents programming constructs like functions or constructors in the context\nof call hierarchy.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "CallHierarchyOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Call hierarchy options used during static or dynamic registration.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyIncomingCallsParams", + "properties": [ + { + "name": "item", + "type": { + "kind": "reference", + "name": "CallHierarchyItem" + } + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameter of a `callHierarchy/incomingCalls` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyIncomingCall", + "properties": [ + { + "name": "from", + "type": { + "kind": "reference", + "name": "CallHierarchyItem" + }, + "documentation": "The item that makes the call." + }, + { + "name": "fromRanges", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Range" + } + }, + "documentation": "The ranges at which the calls appear. This is relative to the caller\ndenoted by [`this.from`](#CallHierarchyIncomingCall.from)." + } + ], + "documentation": "Represents an incoming call, e.g. a caller of a method or constructor.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyOutgoingCallsParams", + "properties": [ + { + "name": "item", + "type": { + "kind": "reference", + "name": "CallHierarchyItem" + } + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameter of a `callHierarchy/outgoingCalls` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CallHierarchyOutgoingCall", + "properties": [ + { + "name": "to", + "type": { + "kind": "reference", + "name": "CallHierarchyItem" + }, + "documentation": "The item that is called." + }, + { + "name": "fromRanges", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Range" + } + }, + "documentation": "The range at which this item is called. This is the range relative to the caller, e.g the item\npassed to [`provideCallHierarchyOutgoingCalls`](#CallHierarchyItemProvider.provideCallHierarchyOutgoingCalls)\nand not [`this.to`](#CallHierarchyOutgoingCall.to)." + } + ], + "documentation": "Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokens", + "properties": [ + { + "name": "resultId", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional result id. If provided and clients support delta updating\nthe client will include the result id in the next semantic token request.\nA server can then instead of computing all semantic tokens again simply\nsend a delta." + }, + { + "name": "data", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "uinteger" + } + }, + "documentation": "The actual tokens." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensPartialResult", + "properties": [ + { + "name": "data", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "uinteger" + } + } + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "SemanticTokensOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensDeltaParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "previousResultId", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The result id of a previous response. The result Id can either point to a full response\nor a delta response depending on what was received last." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensDelta", + "properties": [ + { + "name": "resultId", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true + }, + { + "name": "edits", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SemanticTokensEdit" + } + }, + "documentation": "The semantic token edits to transform a previous result into a new result." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensDeltaPartialResult", + "properties": [ + { + "name": "edits", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SemanticTokensEdit" + } + } + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensRangeParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range the semantic tokens are requested for." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "ShowDocumentParams", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "The document uri to show." + }, + { + "name": "external", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Indicates to show the resource in an external program.\nTo show for example `https://code.visualstudio.com/`\nin the default WEB browser set `external` to `true`." + }, + { + "name": "takeFocus", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "An optional property to indicate whether the editor\nshowing the document should take focus or not.\nClients might ignore this property if an external\nprogram is started." + }, + { + "name": "selection", + "type": { + "kind": "reference", + "name": "Range" + }, + "optional": true, + "documentation": "An optional selection range if the document is a text\ndocument. Clients might ignore the property if an\nexternal program is started or the file is not a text\nfile." + } + ], + "documentation": "Params to show a document.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "ShowDocumentResult", + "properties": [ + { + "name": "success", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "A boolean indicating if the show was successful." + } + ], + "documentation": "The result of a showDocument request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "LinkedEditingRangeParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ] + }, + { + "name": "LinkedEditingRanges", + "properties": [ + { + "name": "ranges", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Range" + } + }, + "documentation": "A list of ranges that can be edited together. The ranges must have\nidentical length and contain identical text content. The ranges cannot overlap." + }, + { + "name": "wordPattern", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional word pattern (regular expression) that describes valid contents for\nthe given ranges. If no pattern is provided, the client configuration's word\npattern will be used." + } + ], + "documentation": "The result of a linked editing range request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "LinkedEditingRangeRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "LinkedEditingRangeOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ] + }, + { + "name": "CreateFilesParams", + "properties": [ + { + "name": "files", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileCreate" + } + }, + "documentation": "An array of all files/folders created in this operation." + } + ], + "documentation": "The parameters sent in notifications/requests for user-initiated creation of\nfiles.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "WorkspaceEdit", + "properties": [ + { + "name": "changes", + "type": { + "kind": "map", + "key": { + "kind": "base", + "name": "DocumentUri" + }, + "value": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + } + }, + "optional": true, + "documentation": "Holds changes to existing resources." + }, + { + "name": "documentChanges", + "type": { + "kind": "array", + "element": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "TextDocumentEdit" + }, + { + "kind": "reference", + "name": "CreateFile" + }, + { + "kind": "reference", + "name": "RenameFile" + }, + { + "kind": "reference", + "name": "DeleteFile" + } + ] + } + }, + "optional": true, + "documentation": "Depending on the client capability `workspace.workspaceEdit.resourceOperations` document changes\nare either an array of `TextDocumentEdit`s to express changes to n different text documents\nwhere each text document edit addresses a specific version of a text document. Or it can contain\nabove `TextDocumentEdit`s mixed with create, rename and delete file / folder operations.\n\nWhether a client supports versioned document edits is expressed via\n`workspace.workspaceEdit.documentChanges` client capability.\n\nIf a client neither supports `documentChanges` nor `workspace.workspaceEdit.resourceOperations` then\nonly plain `TextEdit`s using the `changes` property are supported." + }, + { + "name": "changeAnnotations", + "type": { + "kind": "map", + "key": { + "kind": "reference", + "name": "ChangeAnnotationIdentifier" + }, + "value": { + "kind": "reference", + "name": "ChangeAnnotation" + } + }, + "optional": true, + "documentation": "A map of change annotations that can be referenced in `AnnotatedTextEdit`s or create, rename and\ndelete file / folder operations.\n\nWhether clients honor this property depends on the client capability `workspace.changeAnnotationSupport`.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "A workspace edit represents changes to many resources managed in the workspace. The edit\nshould either provide `changes` or `documentChanges`. If documentChanges are present\nthey are preferred over `changes` if the client can handle versioned document edits.\n\nSince version 3.13.0 a workspace edit can contain resource operations as well. If resource\noperations are present clients need to execute the operations in the order in which they\nare provided. So a workspace edit for example can consist of the following two changes:\n(1) a create file a.txt and (2) a text document edit which insert text into file a.txt.\n\nAn invalid sequence (e.g. (1) delete file a.txt and (2) insert text into file a.txt) will\ncause failure of the operation. How the client recovers from the failure is described by\nthe client capability: `workspace.workspaceEdit.failureHandling`" + }, + { + "name": "FileOperationRegistrationOptions", + "properties": [ + { + "name": "filters", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileOperationFilter" + } + }, + "documentation": "The actual filters." + } + ], + "documentation": "The options to register for file operations.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "RenameFilesParams", + "properties": [ + { + "name": "files", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileRename" + } + }, + "documentation": "An array of all files/folders renamed in this operation. When a folder is renamed, only\nthe folder will be included, and not its children." + } + ], + "documentation": "The parameters sent in notifications/requests for user-initiated renames of\nfiles.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "DeleteFilesParams", + "properties": [ + { + "name": "files", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileDelete" + } + }, + "documentation": "An array of all files/folders deleted in this operation." + } + ], + "documentation": "The parameters sent in notifications/requests for user-initiated deletes of\nfiles.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MonikerParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ] + }, + { + "name": "Moniker", + "properties": [ + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The scheme of the moniker. For example tsc or .Net" + }, + { + "name": "identifier", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The identifier of the moniker. The value is opaque in LSIF however\nschema owners are allowed to define the structure if they want." + }, + { + "name": "unique", + "type": { + "kind": "reference", + "name": "UniquenessLevel" + }, + "documentation": "The scope in which the moniker is unique" + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "MonikerKind" + }, + "optional": true, + "documentation": "The moniker kind if known." + } + ], + "documentation": "Moniker definition to match LSIF 0.5 moniker definition.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MonikerRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "MonikerOptions" + } + ] + }, + { + "name": "TypeHierarchyPrepareParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameter of a `textDocument/prepareTypeHierarchy` request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TypeHierarchyItem", + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of this item." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "SymbolKind" + }, + "documentation": "The kind of this item." + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "optional": true, + "documentation": "Tags for this item." + }, + { + "name": "detail", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "More detail for this item, e.g. the signature of a function." + }, + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The resource identifier of this item." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range enclosing this symbol not including leading/trailing whitespace\nbut everything else, e.g. comments and code." + }, + { + "name": "selectionRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range that should be selected and revealed when this symbol is being\npicked, e.g. the name of a function. Must be contained by the\n[`range`](#TypeHierarchyItem.range)." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved between a type hierarchy prepare and\nsupertypes or subtypes requests. It could also be used to identify the\ntype hierarchy in the server, helping improve the performance on\nresolving supertypes and subtypes." + } + ], + "documentation": "@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TypeHierarchyRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "TypeHierarchyOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Type hierarchy options used during static or dynamic registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TypeHierarchySupertypesParams", + "properties": [ + { + "name": "item", + "type": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameter of a `typeHierarchy/supertypes` request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TypeHierarchySubtypesParams", + "properties": [ + { + "name": "item", + "type": { + "kind": "reference", + "name": "TypeHierarchyItem" + } + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameter of a `typeHierarchy/subtypes` request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range for which inline values should be computed." + }, + { + "name": "context", + "type": { + "kind": "reference", + "name": "InlineValueContext" + }, + "documentation": "Additional information about the context in which inline values were\nrequested." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "A parameter literal used in inline value requests.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "InlineValueOptions" + }, + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Inline value options used during static or dynamic registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHintParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range for which inlay hints should be computed." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "A parameter literal used in inlay hint requests.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHint", + "properties": [ + { + "name": "position", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The position of this hint." + }, + { + "name": "label", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "InlayHintLabelPart" + } + } + ] + }, + "documentation": "The label of this hint. A human readable string or an array of\nInlayHintLabelPart label parts.\n\n*Note* that neither the string nor the label part can be empty." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "InlayHintKind" + }, + "optional": true, + "documentation": "The kind of this hint. Can be omitted in which case the client\nshould fall back to a reasonable default." + }, + { + "name": "textEdits", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + "optional": true, + "documentation": "Optional text edits that are performed when accepting this inlay hint.\n\n*Note* that edits are expected to change the document so that the inlay\nhint (or its nearest variant) is now part of the document and the inlay\nhint itself is now obsolete." + }, + { + "name": "tooltip", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "MarkupContent" + } + ] + }, + "optional": true, + "documentation": "The tooltip text when you hover over this item." + }, + { + "name": "paddingLeft", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Render padding before the hint.\n\nNote: Padding should use the editor's background color, not the\nbackground color of the hint itself. That means padding can be used\nto visually align/separate an inlay hint." + }, + { + "name": "paddingRight", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Render padding after the hint.\n\nNote: Padding should use the editor's background color, not the\nbackground color of the hint itself. That means padding can be used\nto visually align/separate an inlay hint." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on an inlay hint between\na `textDocument/inlayHint` and a `inlayHint/resolve` request." + } + ], + "documentation": "Inlay hint information.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHintRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "InlayHintOptions" + }, + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Inlay hint options used during static or dynamic registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DocumentDiagnosticParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "identifier", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The additional identifier provided during registration." + }, + { + "name": "previousResultId", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The result id of a previous response if provided." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters of the document diagnostic request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DocumentDiagnosticReportPartialResult", + "properties": [ + { + "name": "relatedDocuments", + "type": { + "kind": "map", + "key": { + "kind": "base", + "name": "DocumentUri" + }, + "value": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "FullDocumentDiagnosticReport" + }, + { + "kind": "reference", + "name": "UnchangedDocumentDiagnosticReport" + } + ] + } + } + } + ], + "documentation": "A partial result for a document diagnostic report.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DiagnosticServerCancellationData", + "properties": [ + { + "name": "retriggerRequest", + "type": { + "kind": "base", + "name": "boolean" + } + } + ], + "documentation": "Cancellation data returned from a diagnostic request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DiagnosticRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DiagnosticOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Diagnostic registration options.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceDiagnosticParams", + "properties": [ + { + "name": "identifier", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The additional identifier provided during registration." + }, + { + "name": "previousResultIds", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "PreviousResultId" + } + }, + "documentation": "The currently known diagnostic reports with their\nprevious result ids." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters of the workspace diagnostic request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceDiagnosticReport", + "properties": [ + { + "name": "items", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceDocumentDiagnosticReport" + } + } + } + ], + "documentation": "A workspace diagnostic report.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceDiagnosticReportPartialResult", + "properties": [ + { + "name": "items", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceDocumentDiagnosticReport" + } + } + } + ], + "documentation": "A partial result for a workspace diagnostic report.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DidOpenNotebookDocumentParams", + "properties": [ + { + "name": "notebookDocument", + "type": { + "kind": "reference", + "name": "NotebookDocument" + }, + "documentation": "The notebook document that got opened." + }, + { + "name": "cellTextDocuments", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentItem" + } + }, + "documentation": "The text documents that represent the content\nof a notebook cell." + } + ], + "documentation": "The params sent in an open notebook document notification.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DidChangeNotebookDocumentParams", + "properties": [ + { + "name": "notebookDocument", + "type": { + "kind": "reference", + "name": "VersionedNotebookDocumentIdentifier" + }, + "documentation": "The notebook document that did change. The version number points\nto the version after all provided changes have been applied. If\nonly the text document content of a cell changes the notebook version\ndoesn't necessarily have to change." + }, + { + "name": "change", + "type": { + "kind": "reference", + "name": "NotebookDocumentChangeEvent" + }, + "documentation": "The actual changes to the notebook document.\n\nThe changes describe single state changes to the notebook document.\nSo if there are two changes c1 (at array index 0) and c2 (at array\nindex 1) for a notebook in state S then c1 moves the notebook from\nS to S' and c2 from S' to S''. So c1 is computed on the state S and\nc2 is computed on the state S'.\n\nTo mirror the content of a notebook using change events use the following approach:\n- start with the same initial content\n- apply the 'notebookDocument/didChange' notifications in the order you receive them.\n- apply the `NotebookChangeEvent`s in a single notification in the order\n you receive them." + } + ], + "documentation": "The params sent in a change notebook document notification.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DidSaveNotebookDocumentParams", + "properties": [ + { + "name": "notebookDocument", + "type": { + "kind": "reference", + "name": "NotebookDocumentIdentifier" + }, + "documentation": "The notebook document that got saved." + } + ], + "documentation": "The params sent in a save notebook document notification.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DidCloseNotebookDocumentParams", + "properties": [ + { + "name": "notebookDocument", + "type": { + "kind": "reference", + "name": "NotebookDocumentIdentifier" + }, + "documentation": "The notebook document that got closed." + }, + { + "name": "cellTextDocuments", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentIdentifier" + } + }, + "documentation": "The text documents that represent the content\nof a notebook cell that got closed." + } + ], + "documentation": "The params sent in a close notebook document notification.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "RegistrationParams", + "properties": [ + { + "name": "registrations", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Registration" + } + } + } + ] + }, + { + "name": "UnregistrationParams", + "properties": [ + { + "name": "unregisterations", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Unregistration" + } + } + } + ] + }, + { + "name": "InitializeParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "_InitializeParams" + }, + { + "kind": "reference", + "name": "WorkspaceFoldersInitializeParams" + } + ] + }, + { + "name": "InitializeResult", + "properties": [ + { + "name": "capabilities", + "type": { + "kind": "reference", + "name": "ServerCapabilities" + }, + "documentation": "The capabilities the language server provides." + }, + { + "name": "serverInfo", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of the server as defined by the server." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The server's version as defined by the server." + } + ] + } + }, + "optional": true, + "documentation": "Information about the server.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "documentation": "The result returned from an initialize request." + }, + { + "name": "InitializeError", + "properties": [ + { + "name": "retry", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "Indicates whether the client execute the following retry logic:\n(1) show the message provided by the ResponseError to the user\n(2) user selects retry or cancel\n(3) if user selected retry the initialize method is sent again." + } + ], + "documentation": "The data type of the ResponseError if the\ninitialize request fails." + }, + { + "name": "InitializedParams", + "properties": [] + }, + { + "name": "DidChangeConfigurationParams", + "properties": [ + { + "name": "settings", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "documentation": "The actual changed settings" + } + ], + "documentation": "The parameters of a change configuration notification." + }, + { + "name": "DidChangeConfigurationRegistrationOptions", + "properties": [ + { + "name": "section", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + } + ] + }, + "optional": true + } + ] + }, + { + "name": "ShowMessageParams", + "properties": [ + { + "name": "type", + "type": { + "kind": "reference", + "name": "MessageType" + }, + "documentation": "The message type. See {@link MessageType}" + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The actual message." + } + ], + "documentation": "The parameters of a notification message." + }, + { + "name": "ShowMessageRequestParams", + "properties": [ + { + "name": "type", + "type": { + "kind": "reference", + "name": "MessageType" + }, + "documentation": "The message type. See {@link MessageType}" + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The actual message." + }, + { + "name": "actions", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "MessageActionItem" + } + }, + "optional": true, + "documentation": "The message action items to present." + } + ] + }, + { + "name": "MessageActionItem", + "properties": [ + { + "name": "title", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A short title like 'Retry', 'Open Log' etc." + } + ] + }, + { + "name": "LogMessageParams", + "properties": [ + { + "name": "type", + "type": { + "kind": "reference", + "name": "MessageType" + }, + "documentation": "The message type. See {@link MessageType}" + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The actual message." + } + ], + "documentation": "The log message parameters." + }, + { + "name": "DidOpenTextDocumentParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentItem" + }, + "documentation": "The document that was opened." + } + ], + "documentation": "The parameters sent in an open text document notification" + }, + { + "name": "DidChangeTextDocumentParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "VersionedTextDocumentIdentifier" + }, + "documentation": "The document that did change. The version number points\nto the version after all provided content changes have\nbeen applied." + }, + { + "name": "contentChanges", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentContentChangeEvent" + } + }, + "documentation": "The actual content changes. The content changes describe single state changes\nto the document. So if there are two content changes c1 (at array index 0) and\nc2 (at array index 1) for a document in state S then c1 moves the document from\nS to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed\non the state S'.\n\nTo mirror the content of a document using change events use the following approach:\n- start with the same initial content\n- apply the 'textDocument/didChange' notifications in the order you receive them.\n- apply the `TextDocumentContentChangeEvent`s in a single notification in the order\n you receive them." + } + ], + "documentation": "The change text document notification's parameters." + }, + { + "name": "TextDocumentChangeRegistrationOptions", + "properties": [ + { + "name": "syncKind", + "type": { + "kind": "reference", + "name": "TextDocumentSyncKind" + }, + "documentation": "How documents are synced to the server." + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + } + ], + "documentation": "Describe options to be used when registered for text document change events." + }, + { + "name": "DidCloseTextDocumentParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document that was closed." + } + ], + "documentation": "The parameters sent in a close text document notification" + }, + { + "name": "DidSaveTextDocumentParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document that was saved." + }, + { + "name": "text", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "Optional the content when saved. Depends on the includeText value\nwhen the save notification was requested." + } + ], + "documentation": "The parameters sent in a save text document notification" + }, + { + "name": "TextDocumentSaveRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "SaveOptions" + } + ], + "documentation": "Save registration options." + }, + { + "name": "WillSaveTextDocumentParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document that will be saved." + }, + { + "name": "reason", + "type": { + "kind": "reference", + "name": "TextDocumentSaveReason" + }, + "documentation": "The 'TextDocumentSaveReason'." + } + ], + "documentation": "The parameters sent in a will save text document notification." + }, + { + "name": "TextEdit", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range of the text document to be manipulated. To insert\ntext into a document create a range where start === end." + }, + { + "name": "newText", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The string to be inserted. For delete operations use an\nempty string." + } + ], + "documentation": "A text edit applicable to a text document." + }, + { + "name": "DidChangeWatchedFilesParams", + "properties": [ + { + "name": "changes", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileEvent" + } + }, + "documentation": "The actual file events." + } + ], + "documentation": "The watched files change notification's parameters." + }, + { + "name": "DidChangeWatchedFilesRegistrationOptions", + "properties": [ + { + "name": "watchers", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FileSystemWatcher" + } + }, + "documentation": "The watchers to register." + } + ], + "documentation": "Describe options to be used when registered for text document change events." + }, + { + "name": "PublishDiagnosticsParams", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The URI for which diagnostic information is reported." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "integer" + }, + "optional": true, + "documentation": "Optional the version number of the document the diagnostics are published for.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "diagnostics", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Diagnostic" + } + }, + "documentation": "An array of diagnostic information items." + } + ], + "documentation": "The publish diagnostic notification's parameters." + }, + { + "name": "CompletionParams", + "properties": [ + { + "name": "context", + "type": { + "kind": "reference", + "name": "CompletionContext" + }, + "optional": true, + "documentation": "The completion context. This is only available it the client specifies\nto send this using the client capability `textDocument.completion.contextSupport === true`" + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Completion parameters" + }, + { + "name": "CompletionItem", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The label of this completion item.\n\nThe label property is also by default the text that\nis inserted when selecting this completion.\n\nIf label details are provided the label itself should\nbe an unqualified name of the completion item." + }, + { + "name": "labelDetails", + "type": { + "kind": "reference", + "name": "CompletionItemLabelDetails" + }, + "optional": true, + "documentation": "Additional details for the label\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "CompletionItemKind" + }, + "optional": true, + "documentation": "The kind of this completion item. Based of the kind\nan icon is chosen by the editor." + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItemTag" + } + }, + "optional": true, + "documentation": "Tags for this completion item.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "detail", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A human-readable string with additional information\nabout this item, like type or symbol information." + }, + { + "name": "documentation", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "MarkupContent" + } + ] + }, + "optional": true, + "documentation": "A human-readable string that represents a doc-comment." + }, + { + "name": "deprecated", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Indicates if this item is deprecated.\n@deprecated Use `tags` instead." + }, + { + "name": "preselect", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Select this item when showing.\n\n*Note* that only one completion item can be selected and that the\ntool / client decides which item that is. The rule is that the *first*\nitem of those that match best is selected." + }, + { + "name": "sortText", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A string that should be used when comparing this item\nwith other items. When `falsy` the [label](#CompletionItem.label)\nis used." + }, + { + "name": "filterText", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A string that should be used when filtering a set of\ncompletion items. When `falsy` the [label](#CompletionItem.label)\nis used." + }, + { + "name": "insertText", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A string that should be inserted into a document when selecting\nthis completion. When `falsy` the [label](#CompletionItem.label)\nis used.\n\nThe `insertText` is subject to interpretation by the client side.\nSome tools might not take the string literally. For example\nVS Code when code complete is requested in this example\n`con` and a completion item with an `insertText` of\n`console` is provided it will only insert `sole`. Therefore it is\nrecommended to use `textEdit` instead since it avoids additional client\nside interpretation." + }, + { + "name": "insertTextFormat", + "type": { + "kind": "reference", + "name": "InsertTextFormat" + }, + "optional": true, + "documentation": "The format of the insert text. The format applies to both the\n`insertText` property and the `newText` property of a provided\n`textEdit`. If omitted defaults to `InsertTextFormat.PlainText`.\n\nPlease note that the insertTextFormat doesn't apply to\n`additionalTextEdits`." + }, + { + "name": "insertTextMode", + "type": { + "kind": "reference", + "name": "InsertTextMode" + }, + "optional": true, + "documentation": "How whitespace and indentation is handled during completion\nitem insertion. If not provided the clients default value depends on\nthe `textDocument.completion.insertTextMode` client capability.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "textEdit", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "TextEdit" + }, + { + "kind": "reference", + "name": "InsertReplaceEdit" + } + ] + }, + "optional": true, + "documentation": "An [edit](#TextEdit) which is applied to a document when selecting\nthis completion. When an edit is provided the value of\n[insertText](#CompletionItem.insertText) is ignored.\n\nMost editors support two different operations when accepting a completion\nitem. One is to insert a completion text and the other is to replace an\nexisting text with a completion text. Since this can usually not be\npredetermined by a server it can report both ranges. Clients need to\nsignal support for `InsertReplaceEdits` via the\n`textDocument.completion.insertReplaceSupport` client capability\nproperty.\n\n*Note 1:* The text edit's range as well as both ranges from an insert\nreplace edit must be a [single line] and they must contain the position\nat which completion has been requested.\n*Note 2:* If an `InsertReplaceEdit` is returned the edit's insert range\nmust be a prefix of the edit's replace range, that means it must be\ncontained and starting at the same position.\n\n@since 3.16.0 additional type `InsertReplaceEdit`", + "since": "3.16.0 additional type `InsertReplaceEdit`" + }, + { + "name": "textEditText", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The edit text used if the completion item is part of a CompletionList and\nCompletionList defines an item default for the text edit range.\n\nClients will only honor this property if they opt into completion list\nitem defaults using the capability `completionList.itemDefaults`.\n\nIf not provided and a list's default range is provided the label\nproperty is used as a text.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "additionalTextEdits", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextEdit" + } + }, + "optional": true, + "documentation": "An optional array of additional [text edits](#TextEdit) that are applied when\nselecting this completion. Edits must not overlap (including the same insert position)\nwith the main [edit](#CompletionItem.textEdit) nor with themselves.\n\nAdditional text edits should be used to change text unrelated to the current cursor position\n(for example adding an import statement at the top of the file if the completion item will\ninsert an unqualified type)." + }, + { + "name": "commitCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "An optional set of characters that when pressed while this completion is active will accept it first and\nthen type that character. *Note* that all commit characters should have `length=1` and that superfluous\ncharacters will be ignored." + }, + { + "name": "command", + "type": { + "kind": "reference", + "name": "Command" + }, + "optional": true, + "documentation": "An optional [command](#Command) that is executed *after* inserting this completion. *Note* that\nadditional modifications to the current document should be described with the\n[additionalTextEdits](#CompletionItem.additionalTextEdits)-property." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on a completion item between a\n[CompletionRequest](#CompletionRequest) and a [CompletionResolveRequest](#CompletionResolveRequest)." + } + ], + "documentation": "A completion item represents a text snippet that is\nproposed to complete text that is being typed." + }, + { + "name": "CompletionList", + "properties": [ + { + "name": "isIncomplete", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "This list it not complete. Further typing results in recomputing this list.\n\nRecomputed lists have all their items replaced (not appended) in the\nincomplete completion sessions." + }, + { + "name": "itemDefaults", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "commitCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "A default commit character set.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "editRange", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Range" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "insert", + "type": { + "kind": "reference", + "name": "Range" + } + }, + { + "name": "replace", + "type": { + "kind": "reference", + "name": "Range" + } + } + ] + } + } + ] + }, + "optional": true, + "documentation": "A default edit range.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "insertTextFormat", + "type": { + "kind": "reference", + "name": "InsertTextFormat" + }, + "optional": true, + "documentation": "A default insert text format.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "insertTextMode", + "type": { + "kind": "reference", + "name": "InsertTextMode" + }, + "optional": true, + "documentation": "A default insert text mode.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A default data value.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + } + }, + "optional": true, + "documentation": "In many cases the items of an actual completion result share the same\nvalue for properties like `commitCharacters` or the range of a text\nedit. A completion list can therefore define item defaults which will\nbe used if a completion item itself doesn't specify the value.\n\nIf a completion list specifies a default value and a completion item\nalso specifies a corresponding value the one from the item is used.\n\nServers are only allowed to return default values if the client\nsignals support for this via the `completionList.itemDefaults`\ncapability.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "items", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItem" + } + }, + "documentation": "The completion items." + } + ], + "documentation": "Represents a collection of [completion items](#CompletionItem) to be presented\nin the editor." + }, + { + "name": "CompletionRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "CompletionOptions" + } + ], + "documentation": "Registration options for a [CompletionRequest](#CompletionRequest)." + }, + { + "name": "HoverParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "Parameters for a [HoverRequest](#HoverRequest)." + }, + { + "name": "Hover", + "properties": [ + { + "name": "contents", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "MarkupContent" + }, + { + "kind": "reference", + "name": "MarkedString" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "MarkedString" + } + } + ] + }, + "documentation": "The hover's content" + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "optional": true, + "documentation": "An optional range inside the text document that is used to\nvisualize the hover, e.g. by changing the background color." + } + ], + "documentation": "The result of a hover request." + }, + { + "name": "HoverRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "HoverOptions" + } + ], + "documentation": "Registration options for a [HoverRequest](#HoverRequest)." + }, + { + "name": "SignatureHelpParams", + "properties": [ + { + "name": "context", + "type": { + "kind": "reference", + "name": "SignatureHelpContext" + }, + "optional": true, + "documentation": "The signature help context. This is only available if the client specifies\nto send this using the client capability `textDocument.signatureHelp.contextSupport === true`\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "Parameters for a [SignatureHelpRequest](#SignatureHelpRequest)." + }, + { + "name": "SignatureHelp", + "properties": [ + { + "name": "signatures", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SignatureInformation" + } + }, + "documentation": "One or more signatures." + }, + { + "name": "activeSignature", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The active signature. If omitted or the value lies outside the\nrange of `signatures` the value defaults to zero or is ignored if\nthe `SignatureHelp` has no signatures.\n\nWhenever possible implementors should make an active decision about\nthe active signature and shouldn't rely on a default value.\n\nIn future version of the protocol this property might become\nmandatory to better express this." + }, + { + "name": "activeParameter", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The active parameter of the active signature. If omitted or the value\nlies outside the range of `signatures[activeSignature].parameters`\ndefaults to 0 if the active signature has parameters. If\nthe active signature has no parameters it is ignored.\nIn future version of the protocol this property might become\nmandatory to better express the active parameter if the\nactive signature does have any." + } + ], + "documentation": "Signature help represents the signature of something\ncallable. There can be multiple signature but only one\nactive and only one active parameter." + }, + { + "name": "SignatureHelpRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "SignatureHelpOptions" + } + ], + "documentation": "Registration options for a [SignatureHelpRequest](#SignatureHelpRequest)." + }, + { + "name": "DefinitionParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [DefinitionRequest](#DefinitionRequest)." + }, + { + "name": "DefinitionRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DefinitionOptions" + } + ], + "documentation": "Registration options for a [DefinitionRequest](#DefinitionRequest)." + }, + { + "name": "ReferenceParams", + "properties": [ + { + "name": "context", + "type": { + "kind": "reference", + "name": "ReferenceContext" + } + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [ReferencesRequest](#ReferencesRequest)." + }, + { + "name": "ReferenceRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "ReferenceOptions" + } + ], + "documentation": "Registration options for a [ReferencesRequest](#ReferencesRequest)." + }, + { + "name": "DocumentHighlightParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [DocumentHighlightRequest](#DocumentHighlightRequest)." + }, + { + "name": "DocumentHighlight", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range this highlight applies to." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "DocumentHighlightKind" + }, + "optional": true, + "documentation": "The highlight kind, default is [text](#DocumentHighlightKind.Text)." + } + ], + "documentation": "A document highlight is a range inside a text document which deserves\nspecial attention. Usually a document highlight is visualized by changing\nthe background color of its range." + }, + { + "name": "DocumentHighlightRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentHighlightOptions" + } + ], + "documentation": "Registration options for a [DocumentHighlightRequest](#DocumentHighlightRequest)." + }, + { + "name": "DocumentSymbolParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "Parameters for a [DocumentSymbolRequest](#DocumentSymbolRequest)." + }, + { + "name": "SymbolInformation", + "properties": [ + { + "name": "deprecated", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Indicates if this symbol is deprecated.\n\n@deprecated Use tags instead" + }, + { + "name": "location", + "type": { + "kind": "reference", + "name": "Location" + }, + "documentation": "The location of this symbol. The location's range is used by a tool\nto reveal the location in the editor. If the symbol is selected in the\ntool the range's start information is used to position the cursor. So\nthe range usually spans more than the actual symbol's name and does\nnormally include things like visibility modifiers.\n\nThe range doesn't have to denote a node range in the sense of an abstract\nsyntax tree. It can therefore not be used to re-construct a hierarchy of\nthe symbols." + } + ], + "extends": [ + { + "kind": "reference", + "name": "BaseSymbolInformation" + } + ], + "documentation": "Represents information about programming constructs like variables, classes,\ninterfaces etc." + }, + { + "name": "DocumentSymbol", + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of this symbol. Will be displayed in the user interface and therefore must not be\nan empty string or a string only consisting of white spaces." + }, + { + "name": "detail", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "More detail for this symbol, e.g the signature of a function." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "SymbolKind" + }, + "documentation": "The kind of this symbol." + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "optional": true, + "documentation": "Tags for this document symbol.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "deprecated", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Indicates if this symbol is deprecated.\n\n@deprecated Use tags instead" + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range enclosing this symbol not including leading/trailing whitespace but everything else\nlike comments. This information is typically used to determine if the clients cursor is\ninside the symbol to reveal in the symbol in the UI." + }, + { + "name": "selectionRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range that should be selected and revealed when this symbol is being picked, e.g the name of a function.\nMust be contained by the `range`." + }, + { + "name": "children", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentSymbol" + } + }, + "optional": true, + "documentation": "Children of this symbol, e.g. properties of a class." + } + ], + "documentation": "Represents programming constructs like variables, classes, interfaces etc.\nthat appear in a document. Document symbols can be hierarchical and they\nhave two ranges: one that encloses its definition and one that points to\nits most interesting range, e.g. the range of an identifier." + }, + { + "name": "DocumentSymbolRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentSymbolOptions" + } + ], + "documentation": "Registration options for a [DocumentSymbolRequest](#DocumentSymbolRequest)." + }, + { + "name": "CodeActionParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document in which the command was invoked." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range for which the command was invoked." + }, + { + "name": "context", + "type": { + "kind": "reference", + "name": "CodeActionContext" + }, + "documentation": "Context carrying additional information." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameters of a [CodeActionRequest](#CodeActionRequest)." + }, + { + "name": "Command", + "properties": [ + { + "name": "title", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "Title of the command, like `save`." + }, + { + "name": "command", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The identifier of the actual command handler." + }, + { + "name": "arguments", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "LSPAny" + } + }, + "optional": true, + "documentation": "Arguments that the command handler should be\ninvoked with." + } + ], + "documentation": "Represents a reference to a command. Provides a title which\nwill be used to represent a command in the UI and, optionally,\nan array of arguments which will be passed to the command handler\nfunction when invoked." + }, + { + "name": "CodeAction", + "properties": [ + { + "name": "title", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A short, human-readable, title for this code action." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "CodeActionKind" + }, + "optional": true, + "documentation": "The kind of the code action.\n\nUsed to filter code actions." + }, + { + "name": "diagnostics", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Diagnostic" + } + }, + "optional": true, + "documentation": "The diagnostics that this code action resolves." + }, + { + "name": "isPreferred", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted\nby keybindings.\n\nA quick fix should be marked preferred if it properly addresses the underlying error.\nA refactoring should be marked preferred if it is the most reasonable choice of actions to take.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "disabled", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "reason", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "Human readable description of why the code action is currently disabled.\n\nThis is displayed in the code actions UI." + } + ] + } + }, + "optional": true, + "documentation": "Marks that the code action cannot currently be applied.\n\nClients should follow the following guidelines regarding disabled code actions:\n\n - Disabled code actions are not shown in automatic [lightbulbs](https://code.visualstudio.com/docs/editor/editingevolved#_code-action)\n code action menus.\n\n - Disabled actions are shown as faded out in the code action menu when the user requests a more specific type\n of code action, such as refactorings.\n\n - If the user has a [keybinding](https://code.visualstudio.com/docs/editor/refactoring#_keybindings-for-code-actions)\n that auto applies a code action and only disabled code actions are returned, the client should show the user an\n error message with `reason` in the editor.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "edit", + "type": { + "kind": "reference", + "name": "WorkspaceEdit" + }, + "optional": true, + "documentation": "The workspace edit this code action performs." + }, + { + "name": "command", + "type": { + "kind": "reference", + "name": "Command" + }, + "optional": true, + "documentation": "A command this code action executes. If a code action\nprovides an edit and a command, first the edit is\nexecuted and then the command." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on a code action between\na `textDocument/codeAction` and a `codeAction/resolve` request.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "A code action represents a change that can be performed in code, e.g. to fix a problem or\nto refactor code.\n\nA CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed." + }, + { + "name": "CodeActionRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "CodeActionOptions" + } + ], + "documentation": "Registration options for a [CodeActionRequest](#CodeActionRequest)." + }, + { + "name": "WorkspaceSymbolParams", + "properties": [ + { + "name": "query", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A query string to filter symbols by. Clients may send an empty\nstring here to request all symbols." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameters of a [WorkspaceSymbolRequest](#WorkspaceSymbolRequest)." + }, + { + "name": "WorkspaceSymbol", + "properties": [ + { + "name": "location", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Location" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + } + } + ] + } + } + ] + }, + "documentation": "The location of the symbol. Whether a server is allowed to\nreturn a location without a range depends on the client\ncapability `workspace.symbol.resolveSupport`.\n\nSee SymbolInformation#location for more details." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on a workspace symbol between a\nworkspace symbol request and a workspace symbol resolve request." + } + ], + "extends": [ + { + "kind": "reference", + "name": "BaseSymbolInformation" + } + ], + "documentation": "A special workspace symbol that supports locations without a range.\n\nSee also SymbolInformation.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceSymbolRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "WorkspaceSymbolOptions" + } + ], + "documentation": "Registration options for a [WorkspaceSymbolRequest](#WorkspaceSymbolRequest)." + }, + { + "name": "CodeLensParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to request code lens for." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameters of a [CodeLensRequest](#CodeLensRequest)." + }, + { + "name": "CodeLens", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range in which this code lens is valid. Should only span a single line." + }, + { + "name": "command", + "type": { + "kind": "reference", + "name": "Command" + }, + "optional": true, + "documentation": "The command this code lens represents." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on a code lens item between\na [CodeLensRequest](#CodeLensRequest) and a [CodeLensResolveRequest]\n(#CodeLensResolveRequest)" + } + ], + "documentation": "A code lens represents a [command](#Command) that should be shown along with\nsource text, like the number of references, a way to run tests, etc.\n\nA code lens is _unresolved_ when no command is associated to it. For performance\nreasons the creation of a code lens and resolving should be done in two stages." + }, + { + "name": "CodeLensRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "CodeLensOptions" + } + ], + "documentation": "Registration options for a [CodeLensRequest](#CodeLensRequest)." + }, + { + "name": "DocumentLinkParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to provide document links for." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + }, + { + "kind": "reference", + "name": "PartialResultParams" + } + ], + "documentation": "The parameters of a [DocumentLinkRequest](#DocumentLinkRequest)." + }, + { + "name": "DocumentLink", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range this link applies to." + }, + { + "name": "target", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The uri this link points to. If missing a resolve request is sent later." + }, + { + "name": "tooltip", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The tooltip text when you hover over this link.\n\nIf a tooltip is provided, is will be displayed in a string that includes instructions on how to\ntrigger the link, such as `{0} (ctrl + click)`. The specific instructions vary depending on OS,\nuser settings, and localization.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved on a document link between a\nDocumentLinkRequest and a DocumentLinkResolveRequest." + } + ], + "documentation": "A document link is a range in a text document that links to an internal or external resource, like another\ntext document or a web site." + }, + { + "name": "DocumentLinkRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentLinkOptions" + } + ], + "documentation": "Registration options for a [DocumentLinkRequest](#DocumentLinkRequest)." + }, + { + "name": "DocumentFormattingParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to format." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "FormattingOptions" + }, + "documentation": "The format options." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameters of a [DocumentFormattingRequest](#DocumentFormattingRequest)." + }, + { + "name": "DocumentFormattingRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentFormattingOptions" + } + ], + "documentation": "Registration options for a [DocumentFormattingRequest](#DocumentFormattingRequest)." + }, + { + "name": "DocumentRangeFormattingParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to format." + }, + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range to format" + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "FormattingOptions" + }, + "documentation": "The format options" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameters of a [DocumentRangeFormattingRequest](#DocumentRangeFormattingRequest)." + }, + { + "name": "DocumentRangeFormattingRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentRangeFormattingOptions" + } + ], + "documentation": "Registration options for a [DocumentRangeFormattingRequest](#DocumentRangeFormattingRequest)." + }, + { + "name": "DocumentOnTypeFormattingParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to format." + }, + { + "name": "position", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The position around which the on type formatting should happen.\nThis is not necessarily the exact position where the character denoted\nby the property `ch` got typed." + }, + { + "name": "ch", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The character that has been typed that triggered the formatting\non type request. That is not necessarily the last character that\ngot inserted into the document since the client could auto insert\ncharacters as well (e.g. like automatic brace completion)." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "FormattingOptions" + }, + "documentation": "The formatting options." + } + ], + "documentation": "The parameters of a [DocumentOnTypeFormattingRequest](#DocumentOnTypeFormattingRequest)." + }, + { + "name": "DocumentOnTypeFormattingRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "DocumentOnTypeFormattingOptions" + } + ], + "documentation": "Registration options for a [DocumentOnTypeFormattingRequest](#DocumentOnTypeFormattingRequest)." + }, + { + "name": "RenameParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The document to rename." + }, + { + "name": "position", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The position at which this request was sent." + }, + { + "name": "newName", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The new name of the symbol. If the given name is not valid the\nrequest must return a [ResponseError](#ResponseError) with an\nappropriate message set." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameters of a [RenameRequest](#RenameRequest)." + }, + { + "name": "RenameRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentRegistrationOptions" + }, + { + "kind": "reference", + "name": "RenameOptions" + } + ], + "documentation": "Registration options for a [RenameRequest](#RenameRequest)." + }, + { + "name": "PrepareRenameParams", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentPositionParams" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ] + }, + { + "name": "ExecuteCommandParams", + "properties": [ + { + "name": "command", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The identifier of the actual command handler." + }, + { + "name": "arguments", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "LSPAny" + } + }, + "optional": true, + "documentation": "Arguments that the command should be invoked with." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The parameters of a [ExecuteCommandRequest](#ExecuteCommandRequest)." + }, + { + "name": "ExecuteCommandRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "ExecuteCommandOptions" + } + ], + "documentation": "Registration options for a [ExecuteCommandRequest](#ExecuteCommandRequest)." + }, + { + "name": "ApplyWorkspaceEditParams", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional label of the workspace edit. This label is\npresented in the user interface for example on an undo\nstack to undo the workspace edit." + }, + { + "name": "edit", + "type": { + "kind": "reference", + "name": "WorkspaceEdit" + }, + "documentation": "The edits to apply." + } + ], + "documentation": "The parameters passed via a apply workspace edit request." + }, + { + "name": "ApplyWorkspaceEditResult", + "properties": [ + { + "name": "applied", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "Indicates whether the edit was applied or not." + }, + { + "name": "failureReason", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional textual description for why the edit was not applied.\nThis may be used by the server for diagnostic logging or to provide\na suitable error for a request that triggered the edit." + }, + { + "name": "failedChange", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "Depending on the client's failure handling strategy `failedChange` might\ncontain the index of the change that failed. This property is only available\nif the client signals a `failureHandlingStrategy` in its client capabilities." + } + ], + "documentation": "The result returned from the apply workspace edit request.\n\n@since 3.17 renamed from ApplyWorkspaceEditResponse", + "since": "3.17 renamed from ApplyWorkspaceEditResponse" + }, + { + "name": "WorkDoneProgressBegin", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "begin" + } + }, + { + "name": "title", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "Mandatory title of the progress operation. Used to briefly inform about\nthe kind of operation being performed.\n\nExamples: \"Indexing\" or \"Linking dependencies\"." + }, + { + "name": "cancellable", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Controls if a cancel button should show to allow the user to cancel the\nlong running operation. Clients that don't support cancellation are allowed\nto ignore the setting." + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "Optional, more detailed associated progress message. Contains\ncomplementary information to the `title`.\n\nExamples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\nIf unset, the previous progress message (if any) is still valid." + }, + { + "name": "percentage", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "Optional progress percentage to display (value 100 is considered 100%).\nIf not provided infinite progress is assumed and clients are allowed\nto ignore the `percentage` value in subsequent in report notifications.\n\nThe value should be steadily rising. Clients are free to ignore values\nthat are not following this rule. The value range is [0, 100]." + } + ] + }, + { + "name": "WorkDoneProgressReport", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "report" + } + }, + { + "name": "cancellable", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Controls enablement state of a cancel button.\n\nClients that don't support cancellation or don't support controlling the button's\nenablement state are allowed to ignore the property." + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "Optional, more detailed associated progress message. Contains\ncomplementary information to the `title`.\n\nExamples: \"3/25 files\", \"project/src/module2\", \"node_modules/some_dep\".\nIf unset, the previous progress message (if any) is still valid." + }, + { + "name": "percentage", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "Optional progress percentage to display (value 100 is considered 100%).\nIf not provided infinite progress is assumed and clients are allowed\nto ignore the `percentage` value in subsequent in report notifications.\n\nThe value should be steadily rising. Clients are free to ignore values\nthat are not following this rule. The value range is [0, 100]" + } + ] + }, + { + "name": "WorkDoneProgressEnd", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "end" + } + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "Optional, a final message indicating to for example indicate the outcome\nof the operation." + } + ] + }, + { + "name": "SetTraceParams", + "properties": [ + { + "name": "value", + "type": { + "kind": "reference", + "name": "TraceValues" + } + } + ] + }, + { + "name": "LogTraceParams", + "properties": [ + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + } + }, + { + "name": "verbose", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true + } + ] + }, + { + "name": "CancelParams", + "properties": [ + { + "name": "id", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "string" + } + ] + }, + "documentation": "The request id to cancel." + } + ] + }, + { + "name": "ProgressParams", + "properties": [ + { + "name": "token", + "type": { + "kind": "reference", + "name": "ProgressToken" + }, + "documentation": "The progress token provided by the client or server." + }, + { + "name": "value", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "documentation": "The progress data." + } + ] + }, + { + "name": "TextDocumentPositionParams", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentIdentifier" + }, + "documentation": "The text document." + }, + { + "name": "position", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The position inside the text document." + } + ], + "documentation": "A parameter literal used in requests to pass a text document and a position inside that\ndocument." + }, + { + "name": "WorkDoneProgressParams", + "properties": [ + { + "name": "workDoneToken", + "type": { + "kind": "reference", + "name": "ProgressToken" + }, + "optional": true, + "documentation": "An optional token that a server can use to report work done progress." + } + ] + }, + { + "name": "LocationLink", + "properties": [ + { + "name": "originSelectionRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "optional": true, + "documentation": "Span of the origin of this link.\n\nUsed as the underlined span for mouse interaction. Defaults to the word range at\nthe definition position." + }, + { + "name": "targetUri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The target resource identifier of this link." + }, + { + "name": "targetRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The full target range of this link. If the target for example is a symbol then target range is the\nrange enclosing this symbol not including leading/trailing whitespace but everything else\nlike comments. This information is typically used to highlight the range in the editor." + }, + { + "name": "targetSelectionRange", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range that should be selected and revealed when this link is being followed, e.g the name of a function.\nMust be contained by the `targetRange`. See also `DocumentSymbol#range`" + } + ], + "documentation": "Represents the connection of two locations. Provides additional metadata over normal [locations](#Location),\nincluding an origin range." + }, + { + "name": "Range", + "properties": [ + { + "name": "start", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The range's start position." + }, + { + "name": "end", + "type": { + "kind": "reference", + "name": "Position" + }, + "documentation": "The range's end position." + } + ], + "documentation": "A range in a text document expressed as (zero-based) start and end positions.\n\nIf you want to specify a range that contains a line including the line ending\ncharacter(s) then use an end position denoting the start of the next line.\nFor example:\n```ts\n{\n start: { line: 5, character: 23 }\n end : { line 6, character : 0 }\n}\n```" + }, + { + "name": "ImplementationOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "StaticRegistrationOptions", + "properties": [ + { + "name": "id", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The id used to register the request. The id can be used to deregister\nthe request again. See also Registration#id." + } + ], + "documentation": "Static registration options to be returned in the initialize\nrequest." + }, + { + "name": "TypeDefinitionOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "WorkspaceFoldersChangeEvent", + "properties": [ + { + "name": "added", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceFolder" + } + }, + "documentation": "The array of added workspace folders" + }, + { + "name": "removed", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceFolder" + } + }, + "documentation": "The array of the removed workspace folders" + } + ], + "documentation": "The workspace folder change event." + }, + { + "name": "ConfigurationItem", + "properties": [ + { + "name": "scopeUri", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The scope to get the configuration section for." + }, + { + "name": "section", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The configuration section asked for." + } + ] + }, + { + "name": "TextDocumentIdentifier", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The text document's uri." + } + ], + "documentation": "A literal to identify a text document in the client." + }, + { + "name": "Color", + "properties": [ + { + "name": "red", + "type": { + "kind": "base", + "name": "decimal" + }, + "documentation": "The red component of this color in the range [0-1]." + }, + { + "name": "green", + "type": { + "kind": "base", + "name": "decimal" + }, + "documentation": "The green component of this color in the range [0-1]." + }, + { + "name": "blue", + "type": { + "kind": "base", + "name": "decimal" + }, + "documentation": "The blue component of this color in the range [0-1]." + }, + { + "name": "alpha", + "type": { + "kind": "base", + "name": "decimal" + }, + "documentation": "The alpha component of this color in the range [0-1]." + } + ], + "documentation": "Represents a color in RGBA space." + }, + { + "name": "DocumentColorOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "FoldingRangeOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "DeclarationOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "Position", + "properties": [ + { + "name": "line", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "Line position in a document (zero-based).\n\nIf a line number is greater than the number of lines in a document, it defaults back to the number of lines in the document.\nIf a line number is negative, it defaults to 0." + }, + { + "name": "character", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "Character offset on a line in a document (zero-based).\n\nThe meaning of this offset is determined by the negotiated\n`PositionEncodingKind`.\n\nIf the character value is greater than the line length it defaults back to the\nline length." + } + ], + "documentation": "Position in a text document expressed as zero-based line and character\noffset. Prior to 3.17 the offsets were always based on a UTF-16 string\nrepresentation. So a string of the form `a𐐀b` the character offset of the\ncharacter `a` is 0, the character offset of `𐐀` is 1 and the character\noffset of b is 3 since `𐐀` is represented using two code units in UTF-16.\nSince 3.17 clients and servers can agree on a different string encoding\nrepresentation (e.g. UTF-8). The client announces it's supported encoding\nvia the client capability [`general.positionEncodings`](#clientCapabilities).\nThe value is an array of position encodings the client supports, with\ndecreasing preference (e.g. the encoding at index `0` is the most preferred\none). To stay backwards compatible the only mandatory encoding is UTF-16\nrepresented via the string `utf-16`. The server can pick one of the\nencodings offered by the client and signals that encoding back to the\nclient via the initialize result's property\n[`capabilities.positionEncoding`](#serverCapabilities). If the string value\n`utf-16` is missing from the client's capability `general.positionEncodings`\nservers can safely assume that the client supports UTF-16. If the server\nomits the position encoding in its initialize result the encoding defaults\nto the string value `utf-16`. Implementation considerations: since the\nconversion from one encoding into another requires the content of the\nfile / line the conversion is best done where the file is read which is\nusually on the server side.\n\nPositions are line end character agnostic. So you can not specify a position\nthat denotes `\\r|\\n` or `\\n|` where `|` represents the character offset.\n\n@since 3.17.0 - support for negotiated position encoding.", + "since": "3.17.0 - support for negotiated position encoding." + }, + { + "name": "SelectionRangeOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "CallHierarchyOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Call hierarchy options used during static registration.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensOptions", + "properties": [ + { + "name": "legend", + "type": { + "kind": "reference", + "name": "SemanticTokensLegend" + }, + "documentation": "The legend used by the server" + }, + { + "name": "range", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "literal", + "value": { + "properties": [] + } + } + ] + }, + "optional": true, + "documentation": "Server supports providing semantic tokens for a specific range\nof a document." + }, + { + "name": "full", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "delta", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server supports deltas for full documents." + } + ] + } + } + ] + }, + "optional": true, + "documentation": "Server supports providing semantic tokens for a full document." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensEdit", + "properties": [ + { + "name": "start", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The start offset of the edit." + }, + { + "name": "deleteCount", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The count of elements to remove." + }, + { + "name": "data", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "uinteger" + } + }, + "optional": true, + "documentation": "The elements to insert." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "LinkedEditingRangeOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "FileCreate", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A file:// URI for the location of the file/folder being created." + } + ], + "documentation": "Represents information on a file/folder create.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "TextDocumentEdit", + "properties": [ + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "OptionalVersionedTextDocumentIdentifier" + }, + "documentation": "The text document to change." + }, + { + "name": "edits", + "type": { + "kind": "array", + "element": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "TextEdit" + }, + { + "kind": "reference", + "name": "AnnotatedTextEdit" + } + ] + } + }, + "documentation": "The edits to be applied.\n\n@since 3.16.0 - support for AnnotatedTextEdit. This is guarded using a\nclient capability.", + "since": "3.16.0 - support for AnnotatedTextEdit. This is guarded using a\nclient capability." + } + ], + "documentation": "Describes textual changes on a text document. A TextDocumentEdit describes all changes\non a document version Si and after they are applied move the document to version Si+1.\nSo the creator of a TextDocumentEdit doesn't need to sort the array of edits or do any\nkind of ordering. However the edits must be non overlapping." + }, + { + "name": "CreateFile", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "create" + }, + "documentation": "A create" + }, + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The resource to create." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "CreateFileOptions" + }, + "optional": true, + "documentation": "Additional options" + } + ], + "extends": [ + { + "kind": "reference", + "name": "ResourceOperation" + } + ], + "documentation": "Create file operation." + }, + { + "name": "RenameFile", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "rename" + }, + "documentation": "A rename" + }, + { + "name": "oldUri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The old (existing) location." + }, + { + "name": "newUri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The new location." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "RenameFileOptions" + }, + "optional": true, + "documentation": "Rename options." + } + ], + "extends": [ + { + "kind": "reference", + "name": "ResourceOperation" + } + ], + "documentation": "Rename file operation" + }, + { + "name": "DeleteFile", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "delete" + }, + "documentation": "A delete" + }, + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The file to delete." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "DeleteFileOptions" + }, + "optional": true, + "documentation": "Delete options." + } + ], + "extends": [ + { + "kind": "reference", + "name": "ResourceOperation" + } + ], + "documentation": "Delete file operation" + }, + { + "name": "ChangeAnnotation", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A human-readable string describing the actual change. The string\nis rendered prominent in the user interface." + }, + { + "name": "needsConfirmation", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "A flag which indicates that user confirmation is needed\nbefore applying the change." + }, + { + "name": "description", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A human-readable string which is rendered less prominent in\nthe user interface." + } + ], + "documentation": "Additional information that describes document changes.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "FileOperationFilter", + "properties": [ + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A Uri scheme like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "reference", + "name": "FileOperationPattern" + }, + "documentation": "The actual file operation pattern." + } + ], + "documentation": "A filter to describe in which file operation requests or notifications\nthe server is interested in receiving.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "FileRename", + "properties": [ + { + "name": "oldUri", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A file:// URI for the original location of the file/folder being renamed." + }, + { + "name": "newUri", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A file:// URI for the new location of the file/folder being renamed." + } + ], + "documentation": "Represents information on a file/folder rename.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "FileDelete", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A file:// URI for the location of the file/folder being deleted." + } + ], + "documentation": "Represents information on a file/folder delete.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MonikerOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ] + }, + { + "name": "TypeHierarchyOptions", + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "properties": [], + "documentation": "Type hierarchy options used during static registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueContext", + "properties": [ + { + "name": "frameId", + "type": { + "kind": "base", + "name": "integer" + }, + "documentation": "The stack frame (as a DAP Id) where the execution has stopped." + }, + { + "name": "stoppedLocation", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range where execution has stopped.\nTypically the end position of the range denotes the line where the inline values are shown." + } + ], + "documentation": "@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueText", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range for which the inline value applies." + }, + { + "name": "text", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The text of the inline value." + } + ], + "documentation": "Provide inline value as text.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueVariableLookup", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range for which the inline value applies.\nThe range is used to extract the variable name from the underlying document." + }, + { + "name": "variableName", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "If specified the name of the variable to look up." + }, + { + "name": "caseSensitiveLookup", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "How to perform the lookup." + } + ], + "documentation": "Provide inline value through a variable lookup.\nIf only a range is specified, the variable name will be extracted from the underlying document.\nAn optional variable name can be used to override the extracted name.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueEvaluatableExpression", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The document range for which the inline value applies.\nThe range is used to extract the evaluatable expression from the underlying document." + }, + { + "name": "expression", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "If specified the expression overrides the extracted expression." + } + ], + "documentation": "Provide an inline value through an expression evaluation.\nIf only a range is specified, the expression will be extracted from the underlying document.\nAn optional expression can be used to override the extracted expression.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueOptions", + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "properties": [], + "documentation": "Inline value options used during static registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHintLabelPart", + "properties": [ + { + "name": "value", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The value of this label part." + }, + { + "name": "tooltip", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "MarkupContent" + } + ] + }, + "optional": true, + "documentation": "The tooltip text when you hover over this label part. Depending on\nthe client capability `inlayHint.resolveSupport` clients might resolve\nthis property late using the resolve request." + }, + { + "name": "location", + "type": { + "kind": "reference", + "name": "Location" + }, + "optional": true, + "documentation": "An optional source code location that represents this\nlabel part.\n\nThe editor will use this location for the hover and for code navigation\nfeatures: This part will become a clickable link that resolves to the\ndefinition of the symbol at the given location (not necessarily the\nlocation itself), it shows the hover that shows at the given location,\nand it shows a context menu with further code navigation commands.\n\nDepending on the client capability `inlayHint.resolveSupport` clients\nmight resolve this property late using the resolve request." + }, + { + "name": "command", + "type": { + "kind": "reference", + "name": "Command" + }, + "optional": true, + "documentation": "An optional command for this label part.\n\nDepending on the client capability `inlayHint.resolveSupport` clients\nmight resolve this property late using the resolve request." + } + ], + "documentation": "An inlay hint label part allows for interactive and composite labels\nof inlay hints.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "MarkupContent", + "properties": [ + { + "name": "kind", + "type": { + "kind": "reference", + "name": "MarkupKind" + }, + "documentation": "The type of the Markup" + }, + { + "name": "value", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The content itself" + } + ], + "documentation": "A `MarkupContent` literal represents a string value which content is interpreted base on its\nkind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds.\n\nIf the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues.\nSee https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n\nHere is an example how such a string can be constructed using JavaScript / TypeScript:\n```ts\nlet markdown: MarkdownContent = {\n kind: MarkupKind.Markdown,\n value: [\n '# Header',\n 'Some text',\n '```typescript',\n 'someCode();',\n '```'\n ].join('\\n')\n};\n```\n\n*Please Note* that clients might sanitize the return markdown. A client could decide to\nremove HTML from the markdown to avoid script execution." + }, + { + "name": "InlayHintOptions", + "properties": [ + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server provides support to resolve additional\ninformation for an inlay hint item." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Inlay hint options used during static registration.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "RelatedFullDocumentDiagnosticReport", + "properties": [ + { + "name": "relatedDocuments", + "type": { + "kind": "map", + "key": { + "kind": "base", + "name": "DocumentUri" + }, + "value": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "FullDocumentDiagnosticReport" + }, + { + "kind": "reference", + "name": "UnchangedDocumentDiagnosticReport" + } + ] + } + }, + "optional": true, + "documentation": "Diagnostics of related documents. This information is useful\nin programming languages where code in a file A can generate\ndiagnostics in a file B which A depends on. An example of\nsuch a language is C/C++ where marco definitions in a file\na.cpp and result in errors in a header file b.hpp.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "extends": [ + { + "kind": "reference", + "name": "FullDocumentDiagnosticReport" + } + ], + "documentation": "A full diagnostic report with a set of related documents.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "RelatedUnchangedDocumentDiagnosticReport", + "properties": [ + { + "name": "relatedDocuments", + "type": { + "kind": "map", + "key": { + "kind": "base", + "name": "DocumentUri" + }, + "value": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "FullDocumentDiagnosticReport" + }, + { + "kind": "reference", + "name": "UnchangedDocumentDiagnosticReport" + } + ] + } + }, + "optional": true, + "documentation": "Diagnostics of related documents. This information is useful\nin programming languages where code in a file A can generate\ndiagnostics in a file B which A depends on. An example of\nsuch a language is C/C++ where marco definitions in a file\na.cpp and result in errors in a header file b.hpp.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "extends": [ + { + "kind": "reference", + "name": "UnchangedDocumentDiagnosticReport" + } + ], + "documentation": "An unchanged diagnostic report with a set of related documents.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "FullDocumentDiagnosticReport", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "full" + }, + "documentation": "A full document diagnostic report." + }, + { + "name": "resultId", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional result id. If provided it will\nbe sent on the next diagnostic request for the\nsame document." + }, + { + "name": "items", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Diagnostic" + } + }, + "documentation": "The actual items." + } + ], + "documentation": "A diagnostic report with a full set of problems.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "UnchangedDocumentDiagnosticReport", + "properties": [ + { + "name": "kind", + "type": { + "kind": "stringLiteral", + "value": "unchanged" + }, + "documentation": "A document diagnostic report indicating\nno changes to the last result. A server can\nonly return `unchanged` if result ids are\nprovided." + }, + { + "name": "resultId", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A result id which will be sent on the next\ndiagnostic request for the same document." + } + ], + "documentation": "A diagnostic report indicating that the last returned\nreport is still accurate.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DiagnosticOptions", + "properties": [ + { + "name": "identifier", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional identifier under which the diagnostics are\nmanaged by the client." + }, + { + "name": "interFileDependencies", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "Whether the language has inter file dependencies meaning that\nediting code in one file can result in a different diagnostic\nset in another file. Inter file dependencies are common for\nmost programming languages and typically uncommon for linters." + }, + { + "name": "workspaceDiagnostics", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "The server provides support for workspace diagnostics as well." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Diagnostic options.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "PreviousResultId", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The URI for which the client knowns a\nresult id." + }, + { + "name": "value", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The value of the previous result id." + } + ], + "documentation": "A previous result id in a workspace pull request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocument", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "The notebook document's uri." + }, + { + "name": "notebookType", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The type of the notebook." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "integer" + }, + "documentation": "The version number of this document (it will increase after each\nchange, including undo/redo)." + }, + { + "name": "metadata", + "type": { + "kind": "reference", + "name": "LSPObject" + }, + "optional": true, + "documentation": "Additional metadata stored with the notebook\ndocument.\n\nNote: should always be an object literal (e.g. LSPObject)" + }, + { + "name": "cells", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "NotebookCell" + } + }, + "documentation": "The cells of a notebook." + } + ], + "documentation": "A notebook document.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TextDocumentItem", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The text document's uri." + }, + { + "name": "languageId", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The text document's language identifier." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "integer" + }, + "documentation": "The version number of this document (it will increase after each\nchange, including undo/redo)." + }, + { + "name": "text", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The content of the opened text document." + } + ], + "documentation": "An item to transfer a text document from the client to the\nserver." + }, + { + "name": "VersionedNotebookDocumentIdentifier", + "properties": [ + { + "name": "version", + "type": { + "kind": "base", + "name": "integer" + }, + "documentation": "The version number of this notebook document." + }, + { + "name": "uri", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "The notebook document's uri." + } + ], + "documentation": "A versioned notebook document identifier.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocumentChangeEvent", + "properties": [ + { + "name": "metadata", + "type": { + "kind": "reference", + "name": "LSPObject" + }, + "optional": true, + "documentation": "The changed meta data if any.\n\nNote: should always be an object literal (e.g. LSPObject)" + }, + { + "name": "cells", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "structure", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "array", + "type": { + "kind": "reference", + "name": "NotebookCellArrayChange" + }, + "documentation": "The change to the cell array." + }, + { + "name": "didOpen", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentItem" + } + }, + "optional": true, + "documentation": "Additional opened cell text documents." + }, + { + "name": "didClose", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentIdentifier" + } + }, + "optional": true, + "documentation": "Additional closed cell text documents." + } + ] + } + }, + "optional": true, + "documentation": "Changes to the cell structure to add or\nremove cells." + }, + { + "name": "data", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "NotebookCell" + } + }, + "optional": true, + "documentation": "Changes to notebook cells properties like its\nkind, execution summary or metadata." + }, + { + "name": "textContent", + "type": { + "kind": "array", + "element": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "document", + "type": { + "kind": "reference", + "name": "VersionedTextDocumentIdentifier" + } + }, + { + "name": "changes", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TextDocumentContentChangeEvent" + } + } + } + ] + } + } + }, + "optional": true, + "documentation": "Changes to the text content of notebook cells." + } + ] + } + }, + "optional": true, + "documentation": "Changes to cells" + } + ], + "documentation": "A change event for a notebook document.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocumentIdentifier", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "The notebook document's uri." + } + ], + "documentation": "A literal to identify a notebook document in the client.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "Registration", + "properties": [ + { + "name": "id", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The id used to register the request. The id can be used to deregister\nthe request again." + }, + { + "name": "method", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The method / capability to register for." + }, + { + "name": "registerOptions", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "Options necessary for the registration." + } + ], + "documentation": "General parameters to to register for an notification or to register a provider." + }, + { + "name": "Unregistration", + "properties": [ + { + "name": "id", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The id used to unregister the request or notification. Usually an id\nprovided during the register request." + }, + { + "name": "method", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The method to unregister for." + } + ], + "documentation": "General parameters to unregister a request or notification." + }, + { + "name": "_InitializeParams", + "properties": [ + { + "name": "processId", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The process Id of the parent process that started\nthe server.\n\nIs `null` if the process has not been started by another process.\nIf the parent process is not alive then the server should exit." + }, + { + "name": "clientInfo", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of the client as defined by the client." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The client's version as defined by the client." + } + ] + } + }, + "optional": true, + "documentation": "Information about the client\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "locale", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The locale the client is currently showing the user interface\nin. This must not necessarily be the locale of the operating\nsystem.\n\nUses IETF language tags as the value's syntax\n(See https://en.wikipedia.org/wiki/IETF_language_tag)\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "rootPath", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "optional": true, + "documentation": "The rootPath of the workspace. Is null\nif no folder is open.\n\n@deprecated in favour of rootUri." + }, + { + "name": "rootUri", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "DocumentUri" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The rootUri of the workspace. Is null if no\nfolder is open. If both `rootPath` and `rootUri` are set\n`rootUri` wins.\n\n@deprecated in favour of workspaceFolders." + }, + { + "name": "capabilities", + "type": { + "kind": "reference", + "name": "ClientCapabilities" + }, + "documentation": "The capabilities provided by the client (editor or tool)" + }, + { + "name": "initializationOptions", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "User provided initialization options." + }, + { + "name": "trace", + "type": { + "kind": "or", + "items": [ + { + "kind": "stringLiteral", + "value": "off" + }, + { + "kind": "stringLiteral", + "value": "messages" + }, + { + "kind": "stringLiteral", + "value": "compact" + }, + { + "kind": "stringLiteral", + "value": "verbose" + } + ] + }, + "optional": true, + "documentation": "The initial trace setting. If omitted trace is disabled ('off')." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressParams" + } + ], + "documentation": "The initialize parameters" + }, + { + "name": "WorkspaceFoldersInitializeParams", + "properties": [ + { + "name": "workspaceFolders", + "type": { + "kind": "or", + "items": [ + { + "kind": "array", + "element": { + "kind": "reference", + "name": "WorkspaceFolder" + } + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "optional": true, + "documentation": "The workspace folders configured in the client when the server starts.\n\nThis property is only available if the client supports workspace folders.\nIt can be `null` if the client supports workspace folders but none are\nconfigured.\n\n@since 3.6.0", + "since": "3.6.0" + } + ] + }, + { + "name": "ServerCapabilities", + "properties": [ + { + "name": "positionEncoding", + "type": { + "kind": "reference", + "name": "PositionEncodingKind" + }, + "optional": true, + "documentation": "The position encoding the server picked from the encodings offered\nby the client via the client capability `general.positionEncodings`.\n\nIf the client didn't provide any position encodings the only valid\nvalue that a server can return is 'utf-16'.\n\nIf omitted it defaults to 'utf-16'.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "textDocumentSync", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "TextDocumentSyncOptions" + }, + { + "kind": "reference", + "name": "TextDocumentSyncKind" + } + ] + }, + "optional": true, + "documentation": "Defines how text documents are synced. Is either a detailed structure\ndefining each notification or for backwards compatibility the\nTextDocumentSyncKind number." + }, + { + "name": "notebookDocumentSync", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "NotebookDocumentSyncOptions" + }, + { + "kind": "reference", + "name": "NotebookDocumentSyncRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "Defines how notebook documents are synced.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "completionProvider", + "type": { + "kind": "reference", + "name": "CompletionOptions" + }, + "optional": true, + "documentation": "The server provides completion support." + }, + { + "name": "hoverProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "HoverOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides hover support." + }, + { + "name": "signatureHelpProvider", + "type": { + "kind": "reference", + "name": "SignatureHelpOptions" + }, + "optional": true, + "documentation": "The server provides signature help support." + }, + { + "name": "declarationProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DeclarationOptions" + }, + { + "kind": "reference", + "name": "DeclarationRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides Goto Declaration support." + }, + { + "name": "definitionProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DefinitionOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides goto definition support." + }, + { + "name": "typeDefinitionProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "TypeDefinitionOptions" + }, + { + "kind": "reference", + "name": "TypeDefinitionRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides Goto Type Definition support." + }, + { + "name": "implementationProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "ImplementationOptions" + }, + { + "kind": "reference", + "name": "ImplementationRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides Goto Implementation support." + }, + { + "name": "referencesProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "ReferenceOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides find references support." + }, + { + "name": "documentHighlightProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DocumentHighlightOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides document highlight support." + }, + { + "name": "documentSymbolProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DocumentSymbolOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides document symbol support." + }, + { + "name": "codeActionProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "CodeActionOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides code actions. CodeActionOptions may only be\nspecified if the client states that it supports\n`codeActionLiteralSupport` in its initial `initialize` request." + }, + { + "name": "codeLensProvider", + "type": { + "kind": "reference", + "name": "CodeLensOptions" + }, + "optional": true, + "documentation": "The server provides code lens." + }, + { + "name": "documentLinkProvider", + "type": { + "kind": "reference", + "name": "DocumentLinkOptions" + }, + "optional": true, + "documentation": "The server provides document link support." + }, + { + "name": "colorProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DocumentColorOptions" + }, + { + "kind": "reference", + "name": "DocumentColorRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides color provider support." + }, + { + "name": "workspaceSymbolProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "WorkspaceSymbolOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides workspace symbol support." + }, + { + "name": "documentFormattingProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DocumentFormattingOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides document formatting." + }, + { + "name": "documentRangeFormattingProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "DocumentRangeFormattingOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides document range formatting." + }, + { + "name": "documentOnTypeFormattingProvider", + "type": { + "kind": "reference", + "name": "DocumentOnTypeFormattingOptions" + }, + "optional": true, + "documentation": "The server provides document formatting on typing." + }, + { + "name": "renameProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "RenameOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides rename support. RenameOptions may only be\nspecified if the client states that it supports\n`prepareSupport` in its initial `initialize` request." + }, + { + "name": "foldingRangeProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "FoldingRangeOptions" + }, + { + "kind": "reference", + "name": "FoldingRangeRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides folding provider support." + }, + { + "name": "selectionRangeProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "SelectionRangeOptions" + }, + { + "kind": "reference", + "name": "SelectionRangeRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides selection range support." + }, + { + "name": "executeCommandProvider", + "type": { + "kind": "reference", + "name": "ExecuteCommandOptions" + }, + "optional": true, + "documentation": "The server provides execute command support." + }, + { + "name": "callHierarchyProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "CallHierarchyOptions" + }, + { + "kind": "reference", + "name": "CallHierarchyRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides call hierarchy support.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "linkedEditingRangeProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "LinkedEditingRangeOptions" + }, + { + "kind": "reference", + "name": "LinkedEditingRangeRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides linked editing range support.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "semanticTokensProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "SemanticTokensOptions" + }, + { + "kind": "reference", + "name": "SemanticTokensRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides semantic tokens support.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "monikerProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "MonikerOptions" + }, + { + "kind": "reference", + "name": "MonikerRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides moniker support.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "typeHierarchyProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "TypeHierarchyOptions" + }, + { + "kind": "reference", + "name": "TypeHierarchyRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides type hierarchy support.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "inlineValueProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "InlineValueOptions" + }, + { + "kind": "reference", + "name": "InlineValueRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides inline values.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "inlayHintProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "InlayHintOptions" + }, + { + "kind": "reference", + "name": "InlayHintRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server provides inlay hints.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "diagnosticProvider", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "DiagnosticOptions" + }, + { + "kind": "reference", + "name": "DiagnosticRegistrationOptions" + } + ] + }, + "optional": true, + "documentation": "The server has support for pull model diagnostics.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "workspace", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "workspaceFolders", + "type": { + "kind": "reference", + "name": "WorkspaceFoldersServerCapabilities" + }, + "optional": true, + "documentation": "The server supports workspace folder.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "fileOperations", + "type": { + "kind": "reference", + "name": "FileOperationOptions" + }, + "optional": true, + "documentation": "The server is interested in notifications/requests for operations on files.\n\n@since 3.16.0", + "since": "3.16.0" + } + ] + } + }, + "optional": true, + "documentation": "Workspace specific server capabilities." + }, + { + "name": "experimental", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "Experimental server capabilities." + } + ], + "documentation": "Defines the capabilities provided by a language\nserver." + }, + { + "name": "VersionedTextDocumentIdentifier", + "properties": [ + { + "name": "version", + "type": { + "kind": "base", + "name": "integer" + }, + "documentation": "The version number of this document." + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentIdentifier" + } + ], + "documentation": "A text document identifier to denote a specific version of a text document." + }, + { + "name": "SaveOptions", + "properties": [ + { + "name": "includeText", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client is supposed to include the content on save." + } + ], + "documentation": "Save options." + }, + { + "name": "FileEvent", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The file's uri." + }, + { + "name": "type", + "type": { + "kind": "reference", + "name": "FileChangeType" + }, + "documentation": "The change type." + } + ], + "documentation": "An event describing a file change." + }, + { + "name": "FileSystemWatcher", + "properties": [ + { + "name": "globPattern", + "type": { + "kind": "reference", + "name": "GlobPattern" + }, + "documentation": "The glob pattern to watch. See {@link GlobPattern glob pattern} for more detail.\n\n@since 3.17.0 support for relative patterns.", + "since": "3.17.0 support for relative patterns." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "WatchKind" + }, + "optional": true, + "documentation": "The kind of events of interest. If omitted it defaults\nto WatchKind.Create | WatchKind.Change | WatchKind.Delete\nwhich is 7." + } + ] + }, + { + "name": "Diagnostic", + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range at which the message applies" + }, + { + "name": "severity", + "type": { + "kind": "reference", + "name": "DiagnosticSeverity" + }, + "optional": true, + "documentation": "The diagnostic's severity. Can be omitted. If omitted it is up to the\nclient to interpret diagnostics as error, warning, info or hint." + }, + { + "name": "code", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "string" + } + ] + }, + "optional": true, + "documentation": "The diagnostic's code, which usually appear in the user interface." + }, + { + "name": "codeDescription", + "type": { + "kind": "reference", + "name": "CodeDescription" + }, + "optional": true, + "documentation": "An optional property to describe the error code.\nRequires the code field (above) to be present/not null.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "source", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A human-readable string describing the source of this\ndiagnostic, e.g. 'typescript' or 'super lint'. It usually\nappears in the user interface." + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The diagnostic's message. It usually appears in the user interface" + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DiagnosticTag" + } + }, + "optional": true, + "documentation": "Additional metadata about the diagnostic.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "relatedInformation", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DiagnosticRelatedInformation" + } + }, + "optional": true, + "documentation": "An array of related diagnostic information, e.g. when symbol-names within\na scope collide all definitions can be marked via this property." + }, + { + "name": "data", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "A data entry field that is preserved between a `textDocument/publishDiagnostics`\nnotification and `textDocument/codeAction` request.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "Represents a diagnostic, such as a compiler error or warning. Diagnostic objects\nare only valid in the scope of a resource." + }, + { + "name": "CompletionContext", + "properties": [ + { + "name": "triggerKind", + "type": { + "kind": "reference", + "name": "CompletionTriggerKind" + }, + "documentation": "How the completion was triggered." + }, + { + "name": "triggerCharacter", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The trigger character (a single character) that has trigger code complete.\nIs undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter`" + } + ], + "documentation": "Contains additional information about the context in which a completion request is triggered." + }, + { + "name": "CompletionItemLabelDetails", + "properties": [ + { + "name": "detail", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional string which is rendered less prominently directly after {@link CompletionItem.label label},\nwithout any spacing. Should be used for function signatures and type annotations." + }, + { + "name": "description", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "An optional string which is rendered less prominently after {@link CompletionItem.detail}. Should be used\nfor fully qualified names and file paths." + } + ], + "documentation": "Additional details for a completion item label.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InsertReplaceEdit", + "properties": [ + { + "name": "newText", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The string to be inserted." + }, + { + "name": "insert", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range if the insert is requested" + }, + { + "name": "replace", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range if the replace is requested." + } + ], + "documentation": "A special text edit to provide an insert and a replace operation.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CompletionOptions", + "properties": [ + { + "name": "triggerCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "Most tools trigger completion request automatically without explicitly requesting\nit using a keyboard shortcut (e.g. Ctrl+Space). Typically they do so when the user\nstarts to type an identifier. For example if the user types `c` in a JavaScript file\ncode complete will automatically pop up present `console` besides others as a\ncompletion item. Characters that make up identifiers don't need to be listed here.\n\nIf code complete should automatically be trigger on characters not being valid inside\nan identifier (for example `.` in JavaScript) list them in `triggerCharacters`." + }, + { + "name": "allCommitCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "The list of all possible characters that commit a completion. This field can be used\nif clients don't support individual commit characters per completion item. See\n`ClientCapabilities.textDocument.completion.completionItem.commitCharactersSupport`\n\nIf a server provides both `allCommitCharacters` and commit characters on an individual\ncompletion item the ones on the completion item win.\n\n@since 3.2.0", + "since": "3.2.0" + }, + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server provides support to resolve additional\ninformation for a completion item." + }, + { + "name": "completionItem", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "labelDetailsSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server has support for completion item label\ndetails (see also `CompletionItemLabelDetails`) when\nreceiving a completion item in a resolve call.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + } + }, + "optional": true, + "documentation": "The server supports the following `CompletionItem` specific\ncapabilities.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Completion options." + }, + { + "name": "HoverOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Hover options." + }, + { + "name": "SignatureHelpContext", + "properties": [ + { + "name": "triggerKind", + "type": { + "kind": "reference", + "name": "SignatureHelpTriggerKind" + }, + "documentation": "Action that caused signature help to be triggered." + }, + { + "name": "triggerCharacter", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "Character that caused signature help to be triggered.\n\nThis is undefined when `triggerKind !== SignatureHelpTriggerKind.TriggerCharacter`" + }, + { + "name": "isRetrigger", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "`true` if signature help was already showing when it was triggered.\n\nRetriggers occurs when the signature help is already active and can be caused by actions such as\ntyping a trigger character, a cursor move, or document content changes." + }, + { + "name": "activeSignatureHelp", + "type": { + "kind": "reference", + "name": "SignatureHelp" + }, + "optional": true, + "documentation": "The currently active `SignatureHelp`.\n\nThe `activeSignatureHelp` has its `SignatureHelp.activeSignature` field updated based on\nthe user navigating through available signatures." + } + ], + "documentation": "Additional information about the context in which a signature help request was triggered.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "SignatureInformation", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The label of this signature. Will be shown in\nthe UI." + }, + { + "name": "documentation", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "MarkupContent" + } + ] + }, + "optional": true, + "documentation": "The human-readable doc-comment of this signature. Will be shown\nin the UI but can be omitted." + }, + { + "name": "parameters", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ParameterInformation" + } + }, + "optional": true, + "documentation": "The parameters of this signature." + }, + { + "name": "activeParameter", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The index of the active parameter.\n\nIf provided, this is used in place of `SignatureHelp.activeParameter`.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "Represents the signature of something callable. A signature\ncan have a label, like a function-name, a doc-comment, and\na set of parameters." + }, + { + "name": "SignatureHelpOptions", + "properties": [ + { + "name": "triggerCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "List of characters that trigger signature help automatically." + }, + { + "name": "retriggerCharacters", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "List of characters that re-trigger signature help.\n\nThese trigger characters are only active when signature help is already showing. All trigger characters\nare also counted as re-trigger characters.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Server Capabilities for a [SignatureHelpRequest](#SignatureHelpRequest)." + }, + { + "name": "DefinitionOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Server Capabilities for a [DefinitionRequest](#DefinitionRequest)." + }, + { + "name": "ReferenceContext", + "properties": [ + { + "name": "includeDeclaration", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "Include the declaration of the current symbol." + } + ], + "documentation": "Value-object that contains additional information when\nrequesting references." + }, + { + "name": "ReferenceOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Reference options." + }, + { + "name": "DocumentHighlightOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [DocumentHighlightRequest](#DocumentHighlightRequest)." + }, + { + "name": "BaseSymbolInformation", + "properties": [ + { + "name": "name", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of this symbol." + }, + { + "name": "kind", + "type": { + "kind": "reference", + "name": "SymbolKind" + }, + "documentation": "The kind of this symbol." + }, + { + "name": "tags", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "optional": true, + "documentation": "Tags for this symbol.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "containerName", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The name of the symbol containing this symbol. This information is for\nuser interface purposes (e.g. to render a qualifier in the user interface\nif necessary). It can't be used to re-infer a hierarchy for the document\nsymbols." + } + ], + "documentation": "A base for all symbol information." + }, + { + "name": "DocumentSymbolOptions", + "properties": [ + { + "name": "label", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A human-readable string that is shown when multiple outlines trees\nare shown for the same document.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [DocumentSymbolRequest](#DocumentSymbolRequest)." + }, + { + "name": "CodeActionContext", + "properties": [ + { + "name": "diagnostics", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "Diagnostic" + } + }, + "documentation": "An array of diagnostics known on the client side overlapping the range provided to the\n`textDocument/codeAction` request. They are provided so that the server knows which\nerrors are currently presented to the user for the given range. There is no guarantee\nthat these accurately reflect the error state of the resource. The primary parameter\nto compute code actions is the provided range." + }, + { + "name": "only", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CodeActionKind" + } + }, + "optional": true, + "documentation": "Requested kind of actions to return.\n\nActions not of this kind are filtered out by the client before being shown. So servers\ncan omit computing them." + }, + { + "name": "triggerKind", + "type": { + "kind": "reference", + "name": "CodeActionTriggerKind" + }, + "optional": true, + "documentation": "The reason why code actions were requested.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Contains additional diagnostic information about the context in which\na [code action](#CodeActionProvider.provideCodeActions) is run." + }, + { + "name": "CodeActionOptions", + "properties": [ + { + "name": "codeActionKinds", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CodeActionKind" + } + }, + "optional": true, + "documentation": "CodeActionKinds that this server may return.\n\nThe list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server\nmay list out every specific kind they provide." + }, + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server provides support to resolve additional\ninformation for a code action.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [CodeActionRequest](#CodeActionRequest)." + }, + { + "name": "WorkspaceSymbolOptions", + "properties": [ + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server provides support to resolve additional\ninformation for a workspace symbol.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Server capabilities for a [WorkspaceSymbolRequest](#WorkspaceSymbolRequest)." + }, + { + "name": "CodeLensOptions", + "properties": [ + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Code lens has a resolve provider as well." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Code Lens provider options of a [CodeLensRequest](#CodeLensRequest)." + }, + { + "name": "DocumentLinkOptions", + "properties": [ + { + "name": "resolveProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Document links have a resolve provider as well." + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [DocumentLinkRequest](#DocumentLinkRequest)." + }, + { + "name": "FormattingOptions", + "properties": [ + { + "name": "tabSize", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "Size of a tab in spaces." + }, + { + "name": "insertSpaces", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "Prefer spaces over tabs." + }, + { + "name": "trimTrailingWhitespace", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Trim trailing whitespace on a line.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "insertFinalNewline", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Insert a newline character at the end of the file if one does not exist.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "trimFinalNewlines", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Trim all newlines after the final newline at the end of the file.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "documentation": "Value-object describing what options formatting should use." + }, + { + "name": "DocumentFormattingOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [DocumentFormattingRequest](#DocumentFormattingRequest)." + }, + { + "name": "DocumentRangeFormattingOptions", + "properties": [], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [DocumentRangeFormattingRequest](#DocumentRangeFormattingRequest)." + }, + { + "name": "DocumentOnTypeFormattingOptions", + "properties": [ + { + "name": "firstTriggerCharacter", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A character on which formatting should be triggered, like `{`." + }, + { + "name": "moreTriggerCharacter", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "More trigger characters." + } + ], + "documentation": "Provider options for a [DocumentOnTypeFormattingRequest](#DocumentOnTypeFormattingRequest)." + }, + { + "name": "RenameOptions", + "properties": [ + { + "name": "prepareProvider", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Renames should be checked and tested before being executed.\n\n@since version 3.12.0", + "since": "version 3.12.0" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "Provider options for a [RenameRequest](#RenameRequest)." + }, + { + "name": "ExecuteCommandOptions", + "properties": [ + { + "name": "commands", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The commands to be executed on the server" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "WorkDoneProgressOptions" + } + ], + "documentation": "The server capabilities of a [ExecuteCommandRequest](#ExecuteCommandRequest)." + }, + { + "name": "SemanticTokensLegend", + "properties": [ + { + "name": "tokenTypes", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The token types a server uses." + }, + { + "name": "tokenModifiers", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The token modifiers a server uses." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "OptionalVersionedTextDocumentIdentifier", + "properties": [ + { + "name": "version", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The version number of this document. If a versioned text document identifier\nis sent from the server to the client and the file is not open in the editor\n(the server has not received an open notification before) the server can send\n`null` to indicate that the version is unknown and the content on disk is the\ntruth (as specified with document content ownership)." + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextDocumentIdentifier" + } + ], + "documentation": "A text document identifier to optionally denote a specific version of a text document." + }, + { + "name": "AnnotatedTextEdit", + "properties": [ + { + "name": "annotationId", + "type": { + "kind": "reference", + "name": "ChangeAnnotationIdentifier" + }, + "documentation": "The actual identifier of the change annotation" + } + ], + "extends": [ + { + "kind": "reference", + "name": "TextEdit" + } + ], + "documentation": "A special text edit with an additional change annotation.\n\n@since 3.16.0.", + "since": "3.16.0." + }, + { + "name": "ResourceOperation", + "properties": [ + { + "name": "kind", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The resource operation kind." + }, + { + "name": "annotationId", + "type": { + "kind": "reference", + "name": "ChangeAnnotationIdentifier" + }, + "optional": true, + "documentation": "An optional annotation identifier describing the operation.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "A generic resource operation." + }, + { + "name": "CreateFileOptions", + "properties": [ + { + "name": "overwrite", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Overwrite existing file. Overwrite wins over `ignoreIfExists`" + }, + { + "name": "ignoreIfExists", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Ignore if exists." + } + ], + "documentation": "Options to create a file." + }, + { + "name": "RenameFileOptions", + "properties": [ + { + "name": "overwrite", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Overwrite target if existing. Overwrite wins over `ignoreIfExists`" + }, + { + "name": "ignoreIfExists", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Ignores if target exists." + } + ], + "documentation": "Rename file options" + }, + { + "name": "DeleteFileOptions", + "properties": [ + { + "name": "recursive", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Delete the content recursively if a folder is denoted." + }, + { + "name": "ignoreIfNotExists", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Ignore the operation if the file doesn't exist." + } + ], + "documentation": "Delete file options" + }, + { + "name": "FileOperationPattern", + "properties": [ + { + "name": "glob", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The glob pattern to match. Glob patterns can have the following syntax:\n- `*` to match one or more characters in a path segment\n- `?` to match on one character in a path segment\n- `**` to match any number of path segments, including none\n- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files)\n- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)" + }, + { + "name": "matches", + "type": { + "kind": "reference", + "name": "FileOperationPatternKind" + }, + "optional": true, + "documentation": "Whether to match files or folders with this pattern.\n\nMatches both if undefined." + }, + { + "name": "options", + "type": { + "kind": "reference", + "name": "FileOperationPatternOptions" + }, + "optional": true, + "documentation": "Additional options used during matching." + } + ], + "documentation": "A pattern to describe in which file operation requests or notifications\nthe server is interested in receiving.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "WorkspaceFullDocumentDiagnosticReport", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The URI for which diagnostic information is reported." + }, + { + "name": "version", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The version number for which the diagnostics are reported.\nIf the document is not marked as open `null` can be provided." + } + ], + "extends": [ + { + "kind": "reference", + "name": "FullDocumentDiagnosticReport" + } + ], + "documentation": "A full document diagnostic report for a workspace diagnostic result.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceUnchangedDocumentDiagnosticReport", + "properties": [ + { + "name": "uri", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The URI for which diagnostic information is reported." + }, + { + "name": "version", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The version number for which the diagnostics are reported.\nIf the document is not marked as open `null` can be provided." + } + ], + "extends": [ + { + "kind": "reference", + "name": "UnchangedDocumentDiagnosticReport" + } + ], + "documentation": "An unchanged document diagnostic report for a workspace diagnostic result.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "LSPObject", + "properties": [], + "documentation": "LSP object definition.\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookCell", + "properties": [ + { + "name": "kind", + "type": { + "kind": "reference", + "name": "NotebookCellKind" + }, + "documentation": "The cell's kind" + }, + { + "name": "document", + "type": { + "kind": "base", + "name": "DocumentUri" + }, + "documentation": "The URI of the cell's text document\ncontent." + }, + { + "name": "metadata", + "type": { + "kind": "reference", + "name": "LSPObject" + }, + "optional": true, + "documentation": "Additional metadata stored with the cell.\n\nNote: should always be an object literal (e.g. LSPObject)" + }, + { + "name": "executionSummary", + "type": { + "kind": "reference", + "name": "ExecutionSummary" + }, + "optional": true, + "documentation": "Additional execution summary information\nif supported by the client." + } + ], + "documentation": "A notebook cell.\n\nA cell's document URI must be unique across ALL notebook\ncells and can therefore be used to uniquely identify a\nnotebook cell or the cell's text document.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookCellArrayChange", + "properties": [ + { + "name": "start", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The start oftest of the cell that changed." + }, + { + "name": "deleteCount", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "The deleted cells" + }, + { + "name": "cells", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "NotebookCell" + } + }, + "optional": true, + "documentation": "The new cells, if any" + } + ], + "documentation": "A change describing how to move a `NotebookCell`\narray from state S to S'.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ClientCapabilities", + "properties": [ + { + "name": "workspace", + "type": { + "kind": "reference", + "name": "WorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Workspace specific client capabilities." + }, + { + "name": "textDocument", + "type": { + "kind": "reference", + "name": "TextDocumentClientCapabilities" + }, + "optional": true, + "documentation": "Text document specific client capabilities." + }, + { + "name": "notebookDocument", + "type": { + "kind": "reference", + "name": "NotebookDocumentClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the notebook document support.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "window", + "type": { + "kind": "reference", + "name": "WindowClientCapabilities" + }, + "optional": true, + "documentation": "Window specific client capabilities." + }, + { + "name": "general", + "type": { + "kind": "reference", + "name": "GeneralClientCapabilities" + }, + "optional": true, + "documentation": "General client capabilities.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "experimental", + "type": { + "kind": "reference", + "name": "LSPAny" + }, + "optional": true, + "documentation": "Experimental client capabilities." + } + ], + "documentation": "Defines the capabilities provided by the client." + }, + { + "name": "TextDocumentSyncOptions", + "properties": [ + { + "name": "openClose", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Open and close notifications are sent to the server. If omitted open close notification should not\nbe sent." + }, + { + "name": "change", + "type": { + "kind": "reference", + "name": "TextDocumentSyncKind" + }, + "optional": true, + "documentation": "Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full\nand TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None." + }, + { + "name": "willSave", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "If present will save notifications are sent to the server. If omitted the notification should not be\nsent." + }, + { + "name": "willSaveWaitUntil", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "If present will save wait until requests are sent to the server. If omitted the request should not be\nsent." + }, + { + "name": "save", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "reference", + "name": "SaveOptions" + } + ] + }, + "optional": true, + "documentation": "If present save notifications are sent to the server. If omitted the notification should not be\nsent." + } + ] + }, + { + "name": "NotebookDocumentSyncOptions", + "properties": [ + { + "name": "notebookSelector", + "type": { + "kind": "array", + "element": { + "kind": "or", + "items": [ + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "notebook", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "NotebookDocumentFilter" + } + ] + }, + "documentation": "The notebook to be synced If a string\nvalue is provided it matches against the\nnotebook type. '*' matches every notebook." + }, + { + "name": "cells", + "type": { + "kind": "array", + "element": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + } + } + ] + } + } + }, + "optional": true, + "documentation": "The cells of the matching notebook to be synced." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "notebook", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "NotebookDocumentFilter" + } + ] + }, + "optional": true, + "documentation": "The notebook to be synced If a string\nvalue is provided it matches against the\nnotebook type. '*' matches every notebook." + }, + { + "name": "cells", + "type": { + "kind": "array", + "element": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + } + } + ] + } + } + }, + "documentation": "The cells of the matching notebook to be synced." + } + ] + } + } + ] + } + }, + "documentation": "The notebooks to be synced" + }, + { + "name": "save", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether save notification should be forwarded to\nthe server. Will only be honored if mode === `notebook`." + } + ], + "documentation": "Options specific to a notebook plus its cells\nto be synced to the server.\n\nIf a selector provides a notebook document\nfilter but no cell selector all cells of a\nmatching notebook document will be synced.\n\nIf a selector provides no notebook document\nfilter but only a cell selector all notebook\ndocument that contain at least one matching\ncell will be synced.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocumentSyncRegistrationOptions", + "properties": [], + "extends": [ + { + "kind": "reference", + "name": "NotebookDocumentSyncOptions" + } + ], + "mixins": [ + { + "kind": "reference", + "name": "StaticRegistrationOptions" + } + ], + "documentation": "Registration options specific to a notebook.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceFoldersServerCapabilities", + "properties": [ + { + "name": "supported", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The server has support for workspace folders" + }, + { + "name": "changeNotifications", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "base", + "name": "boolean" + } + ] + }, + "optional": true, + "documentation": "Whether the server wants to receive workspace folder\nchange notifications.\n\nIf a string is provided the string is treated as an ID\nunder which the notification is registered on the client\nside. The ID can be used to unregister for these events\nusing the `client/unregisterCapability` request." + } + ] + }, + { + "name": "FileOperationOptions", + "properties": [ + { + "name": "didCreate", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving didCreateFiles notifications." + }, + { + "name": "willCreate", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving willCreateFiles requests." + }, + { + "name": "didRename", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving didRenameFiles notifications." + }, + { + "name": "willRename", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving willRenameFiles requests." + }, + { + "name": "didDelete", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving didDeleteFiles file notifications." + }, + { + "name": "willDelete", + "type": { + "kind": "reference", + "name": "FileOperationRegistrationOptions" + }, + "optional": true, + "documentation": "The server is interested in receiving willDeleteFiles file requests." + } + ], + "documentation": "Options for notifications/requests for user operations on files.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CodeDescription", + "properties": [ + { + "name": "href", + "type": { + "kind": "base", + "name": "URI" + }, + "documentation": "An URI to open with more information about the diagnostic error." + } + ], + "documentation": "Structure to capture a description for an error code.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "DiagnosticRelatedInformation", + "properties": [ + { + "name": "location", + "type": { + "kind": "reference", + "name": "Location" + }, + "documentation": "The location of this related diagnostic information." + }, + { + "name": "message", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The message of this related diagnostic information." + } + ], + "documentation": "Represents a related message and source code location for a diagnostic. This should be\nused to point to code locations that cause or related to a diagnostics, e.g when duplicating\na symbol in a scope." + }, + { + "name": "ParameterInformation", + "properties": [ + { + "name": "label", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "tuple", + "items": [ + { + "kind": "base", + "name": "uinteger" + }, + { + "kind": "base", + "name": "uinteger" + } + ] + } + ] + }, + "documentation": "The label of this parameter information.\n\nEither a string or an inclusive start and exclusive end offsets within its containing\nsignature label. (see SignatureInformation.label). The offsets are based on a UTF-16\nstring representation as `Position` and `Range` does.\n\n*Note*: a label of type string should be a substring of its containing signature label.\nIts intended use case is to highlight the parameter label part in the `SignatureInformation.label`." + }, + { + "name": "documentation", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "MarkupContent" + } + ] + }, + "optional": true, + "documentation": "The human-readable doc-comment of this parameter. Will be shown\nin the UI but can be omitted." + } + ], + "documentation": "Represents a parameter of a callable-signature. A parameter can\nhave a label and a doc-comment." + }, + { + "name": "NotebookCellTextDocumentFilter", + "properties": [ + { + "name": "notebook", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "reference", + "name": "NotebookDocumentFilter" + } + ] + }, + "documentation": "A filter that matches against the notebook\ncontaining the notebook cell. If a string\nvalue is provided it matches against the\nnotebook type. '*' matches every notebook." + }, + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A language id like `python`.\n\nWill be matched against the language id of the\nnotebook cell document. '*' matches every language." + } + ], + "documentation": "A notebook cell text document filter denotes a cell text\ndocument by different properties.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "FileOperationPatternOptions", + "properties": [ + { + "name": "ignoreCase", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The pattern should be matched ignoring casing." + } + ], + "documentation": "Matching options for the file operation pattern.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "ExecutionSummary", + "properties": [ + { + "name": "executionOrder", + "type": { + "kind": "base", + "name": "uinteger" + }, + "documentation": "A strict monotonically increasing value\nindicating the execution order of a cell\ninside a notebook." + }, + { + "name": "success", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the execution was successful or\nnot if known by the client." + } + ] + }, + { + "name": "WorkspaceClientCapabilities", + "properties": [ + { + "name": "applyEdit", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports applying batch edits\nto the workspace by supporting the request\n'workspace/applyEdit'" + }, + { + "name": "workspaceEdit", + "type": { + "kind": "reference", + "name": "WorkspaceEditClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to `WorkspaceEdit`s." + }, + { + "name": "didChangeConfiguration", + "type": { + "kind": "reference", + "name": "DidChangeConfigurationClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `workspace/didChangeConfiguration` notification." + }, + { + "name": "didChangeWatchedFiles", + "type": { + "kind": "reference", + "name": "DidChangeWatchedFilesClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `workspace/didChangeWatchedFiles` notification." + }, + { + "name": "symbol", + "type": { + "kind": "reference", + "name": "WorkspaceSymbolClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `workspace/symbol` request." + }, + { + "name": "executeCommand", + "type": { + "kind": "reference", + "name": "ExecuteCommandClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `workspace/executeCommand` request." + }, + { + "name": "workspaceFolders", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for workspace folders.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "configuration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports `workspace/configuration` requests.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "semanticTokens", + "type": { + "kind": "reference", + "name": "SemanticTokensWorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the semantic token requests scoped to the\nworkspace.\n\n@since 3.16.0.", + "since": "3.16.0." + }, + { + "name": "codeLens", + "type": { + "kind": "reference", + "name": "CodeLensWorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the code lens requests scoped to the\nworkspace.\n\n@since 3.16.0.", + "since": "3.16.0." + }, + { + "name": "fileOperations", + "type": { + "kind": "reference", + "name": "FileOperationClientCapabilities" + }, + "optional": true, + "documentation": "The client has support for file notifications/requests for user operations on files.\n\nSince 3.16.0" + }, + { + "name": "inlineValue", + "type": { + "kind": "reference", + "name": "InlineValueWorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the inline values requests scoped to the\nworkspace.\n\n@since 3.17.0.", + "since": "3.17.0." + }, + { + "name": "inlayHint", + "type": { + "kind": "reference", + "name": "InlayHintWorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the inlay hint requests scoped to the\nworkspace.\n\n@since 3.17.0.", + "since": "3.17.0." + }, + { + "name": "diagnostics", + "type": { + "kind": "reference", + "name": "DiagnosticWorkspaceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the diagnostic requests scoped to the\nworkspace.\n\n@since 3.17.0.", + "since": "3.17.0." + } + ], + "documentation": "Workspace specific client capabilities." + }, + { + "name": "TextDocumentClientCapabilities", + "properties": [ + { + "name": "synchronization", + "type": { + "kind": "reference", + "name": "TextDocumentSyncClientCapabilities" + }, + "optional": true, + "documentation": "Defines which synchronization capabilities the client supports." + }, + { + "name": "completion", + "type": { + "kind": "reference", + "name": "CompletionClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/completion` request." + }, + { + "name": "hover", + "type": { + "kind": "reference", + "name": "HoverClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/hover` request." + }, + { + "name": "signatureHelp", + "type": { + "kind": "reference", + "name": "SignatureHelpClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/signatureHelp` request." + }, + { + "name": "declaration", + "type": { + "kind": "reference", + "name": "DeclarationClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/declaration` request.\n\n@since 3.14.0", + "since": "3.14.0" + }, + { + "name": "definition", + "type": { + "kind": "reference", + "name": "DefinitionClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/definition` request." + }, + { + "name": "typeDefinition", + "type": { + "kind": "reference", + "name": "TypeDefinitionClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/typeDefinition` request.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "implementation", + "type": { + "kind": "reference", + "name": "ImplementationClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/implementation` request.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "references", + "type": { + "kind": "reference", + "name": "ReferenceClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/references` request." + }, + { + "name": "documentHighlight", + "type": { + "kind": "reference", + "name": "DocumentHighlightClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/documentHighlight` request." + }, + { + "name": "documentSymbol", + "type": { + "kind": "reference", + "name": "DocumentSymbolClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/documentSymbol` request." + }, + { + "name": "codeAction", + "type": { + "kind": "reference", + "name": "CodeActionClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/codeAction` request." + }, + { + "name": "codeLens", + "type": { + "kind": "reference", + "name": "CodeLensClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/codeLens` request." + }, + { + "name": "documentLink", + "type": { + "kind": "reference", + "name": "DocumentLinkClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/documentLink` request." + }, + { + "name": "colorProvider", + "type": { + "kind": "reference", + "name": "DocumentColorClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/documentColor` and the\n`textDocument/colorPresentation` request.\n\n@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "formatting", + "type": { + "kind": "reference", + "name": "DocumentFormattingClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/formatting` request." + }, + { + "name": "rangeFormatting", + "type": { + "kind": "reference", + "name": "DocumentRangeFormattingClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/rangeFormatting` request." + }, + { + "name": "onTypeFormatting", + "type": { + "kind": "reference", + "name": "DocumentOnTypeFormattingClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/onTypeFormatting` request." + }, + { + "name": "rename", + "type": { + "kind": "reference", + "name": "RenameClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/rename` request." + }, + { + "name": "foldingRange", + "type": { + "kind": "reference", + "name": "FoldingRangeClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/foldingRange` request.\n\n@since 3.10.0", + "since": "3.10.0" + }, + { + "name": "selectionRange", + "type": { + "kind": "reference", + "name": "SelectionRangeClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/selectionRange` request.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "publishDiagnostics", + "type": { + "kind": "reference", + "name": "PublishDiagnosticsClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/publishDiagnostics` notification." + }, + { + "name": "callHierarchy", + "type": { + "kind": "reference", + "name": "CallHierarchyClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the various call hierarchy requests.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "semanticTokens", + "type": { + "kind": "reference", + "name": "SemanticTokensClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the various semantic token request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "linkedEditingRange", + "type": { + "kind": "reference", + "name": "LinkedEditingRangeClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/linkedEditingRange` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "moniker", + "type": { + "kind": "reference", + "name": "MonikerClientCapabilities" + }, + "optional": true, + "documentation": "Client capabilities specific to the `textDocument/moniker` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "typeHierarchy", + "type": { + "kind": "reference", + "name": "TypeHierarchyClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the various type hierarchy requests.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "inlineValue", + "type": { + "kind": "reference", + "name": "InlineValueClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/inlineValue` request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "inlayHint", + "type": { + "kind": "reference", + "name": "InlayHintClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the `textDocument/inlayHint` request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "diagnostic", + "type": { + "kind": "reference", + "name": "DiagnosticClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the diagnostic pull model.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Text document specific client capabilities." + }, + { + "name": "NotebookDocumentClientCapabilities", + "properties": [ + { + "name": "synchronization", + "type": { + "kind": "reference", + "name": "NotebookDocumentSyncClientCapabilities" + }, + "documentation": "Capabilities specific to notebook document synchronization\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Capabilities specific to the notebook document support.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WindowClientCapabilities", + "properties": [ + { + "name": "workDoneProgress", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "It indicates whether the client supports server initiated\nprogress using the `window/workDoneProgress/create` request.\n\nThe capability also controls Whether client supports handling\nof progress notifications. If set servers are allowed to report a\n`workDoneProgress` property in the request specific server\ncapabilities.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "showMessage", + "type": { + "kind": "reference", + "name": "ShowMessageRequestClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the showMessage request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "showDocument", + "type": { + "kind": "reference", + "name": "ShowDocumentClientCapabilities" + }, + "optional": true, + "documentation": "Capabilities specific to the showDocument request.\n\n@since 3.16.0", + "since": "3.16.0" + } + ] + }, + { + "name": "GeneralClientCapabilities", + "properties": [ + { + "name": "staleRequestSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "cancel", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "The client will actively cancel the request." + }, + { + "name": "retryOnContentModified", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The list of requests for which the client\nwill retry the request if it receives a\nresponse with error code `ContentModified`" + } + ] + } + }, + "optional": true, + "documentation": "Client capability that signals how the client\nhandles stale requests (e.g. a request\nfor which the client will not process the response\nanymore since the information is outdated).\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "regularExpressions", + "type": { + "kind": "reference", + "name": "RegularExpressionsClientCapabilities" + }, + "optional": true, + "documentation": "Client capabilities specific to regular expressions.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "markdown", + "type": { + "kind": "reference", + "name": "MarkdownClientCapabilities" + }, + "optional": true, + "documentation": "Client capabilities specific to the client's markdown parser.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "positionEncodings", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "PositionEncodingKind" + } + }, + "optional": true, + "documentation": "The position encodings supported by the client. Client and server\nhave to agree on the same position encoding to ensure that offsets\n(e.g. character position in a line) are interpreted the same on both\nsides.\n\nTo keep the protocol backwards compatible the following applies: if\nthe value 'utf-16' is missing from the array of position encodings\nservers can assume that the client supports UTF-16. UTF-16 is\ntherefore a mandatory encoding.\n\nIf omitted it defaults to ['utf-16'].\n\nImplementation considerations: since the conversion from one encoding\ninto another requires the content of the file / line the conversion\nis best done where the file is read which is usually on the server\nside.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "General client capabilities.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "RelativePattern", + "properties": [ + { + "name": "baseUri", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceFolder" + }, + { + "kind": "base", + "name": "URI" + } + ] + }, + "documentation": "A workspace folder or a base URI to which this pattern will be matched\nagainst relatively." + }, + { + "name": "pattern", + "type": { + "kind": "reference", + "name": "Pattern" + }, + "documentation": "The actual glob pattern;" + } + ], + "documentation": "A relative pattern is a helper to construct glob patterns that are matched\nrelatively to a base URI. The common value for a `baseUri` is a workspace\nfolder root, but it can be another absolute URI as well.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "WorkspaceEditClientCapabilities", + "properties": [ + { + "name": "documentChanges", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports versioned document changes in `WorkspaceEdit`s" + }, + { + "name": "resourceOperations", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "ResourceOperationKind" + } + }, + "optional": true, + "documentation": "The resource operations the client supports. Clients should at least\nsupport 'create', 'rename' and 'delete' files and folders.\n\n@since 3.13.0", + "since": "3.13.0" + }, + { + "name": "failureHandling", + "type": { + "kind": "reference", + "name": "FailureHandlingKind" + }, + "optional": true, + "documentation": "The failure handling strategy of a client if applying the workspace edit\nfails.\n\n@since 3.13.0", + "since": "3.13.0" + }, + { + "name": "normalizesLineEndings", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client normalizes line endings to the client specific\nsetting.\nIf set to `true` the client will normalize line ending characters\nin a workspace edit to the client-specified new line\ncharacter.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "changeAnnotationSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "groupsOnLabel", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client groups edits with equal labels into tree nodes,\nfor instance all edits labelled with \"Changes in Strings\" would\nbe a tree node." + } + ] + } + }, + "optional": true, + "documentation": "Whether the client in general supports change annotations on text edits,\ncreate file, rename file and delete file changes.\n\n@since 3.16.0", + "since": "3.16.0" + } + ] + }, + { + "name": "DidChangeConfigurationClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Did change configuration notification supports dynamic registration." + } + ] + }, + { + "name": "DidChangeWatchedFilesClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Did change watched files notification supports dynamic registration. Please note\nthat the current protocol doesn't support static configuration for file changes\nfrom the server side." + }, + { + "name": "relativePatternSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client has support for {@link RelativePattern relative pattern}\nor not.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + }, + { + "name": "WorkspaceSymbolClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Symbol request supports dynamic registration." + }, + { + "name": "symbolKind", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolKind" + } + }, + "optional": true, + "documentation": "The symbol kind values the client supports. When this\nproperty exists the client also guarantees that it will\nhandle values outside its set gracefully and falls back\nto a default value when unknown.\n\nIf this property is not present the client only supports\nthe symbol kinds from `File` to `Array` as defined in\nthe initial version of the protocol." + } + ] + } + }, + "optional": true, + "documentation": "Specific capabilities for the `SymbolKind` in the `workspace/symbol` request." + }, + { + "name": "tagSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "documentation": "The tags supported by the client." + } + ] + } + }, + "optional": true, + "documentation": "The client supports tags on `SymbolInformation`.\nClients supporting tags have to handle unknown tags gracefully.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "resolveSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "properties", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The properties that a client can resolve lazily. Usually\n`location.range`" + } + ] + } + }, + "optional": true, + "documentation": "The client support partial workspace symbols. The client will send the\nrequest `workspaceSymbol/resolve` to the server to resolve additional\nproperties.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Client capabilities for a [WorkspaceSymbolRequest](#WorkspaceSymbolRequest)." + }, + { + "name": "ExecuteCommandClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Execute command supports dynamic registration." + } + ], + "documentation": "The client capabilities of a [ExecuteCommandRequest](#ExecuteCommandRequest)." + }, + { + "name": "SemanticTokensWorkspaceClientCapabilities", + "properties": [ + { + "name": "refreshSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client implementation supports a refresh request sent from\nthe server to the client.\n\nNote that this event is global and will force the client to refresh all\nsemantic tokens currently shown. It should be used with absolute care\nand is useful for situation where a server for example detects a project\nwide change that requires such a calculation." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "CodeLensWorkspaceClientCapabilities", + "properties": [ + { + "name": "refreshSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client implementation supports a refresh request sent from the\nserver to the client.\n\nNote that this event is global and will force the client to refresh all\ncode lenses currently shown. It should be used with absolute care and is\nuseful for situation where a server for example detect a project wide\nchange that requires such a calculation." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "FileOperationClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client supports dynamic registration for file requests/notifications." + }, + { + "name": "didCreate", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending didCreateFiles notifications." + }, + { + "name": "willCreate", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending willCreateFiles requests." + }, + { + "name": "didRename", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending didRenameFiles notifications." + }, + { + "name": "willRename", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending willRenameFiles requests." + }, + { + "name": "didDelete", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending didDeleteFiles notifications." + }, + { + "name": "willDelete", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for sending willDeleteFiles requests." + } + ], + "documentation": "Capabilities relating to events from file operations by the user in the client.\n\nThese events do not come from the file system, they come from user operations\nlike renaming a file in the UI.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "InlineValueWorkspaceClientCapabilities", + "properties": [ + { + "name": "refreshSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client implementation supports a refresh request sent from the\nserver to the client.\n\nNote that this event is global and will force the client to refresh all\ninline values currently shown. It should be used with absolute care and is\nuseful for situation where a server for example detects a project wide\nchange that requires such a calculation." + } + ], + "documentation": "Client workspace capabilities specific to inline values.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHintWorkspaceClientCapabilities", + "properties": [ + { + "name": "refreshSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client implementation supports a refresh request sent from\nthe server to the client.\n\nNote that this event is global and will force the client to refresh all\ninlay hints currently shown. It should be used with absolute care and\nis useful for situation where a server for example detects a project wide\nchange that requires such a calculation." + } + ], + "documentation": "Client workspace capabilities specific to inlay hints.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DiagnosticWorkspaceClientCapabilities", + "properties": [ + { + "name": "refreshSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client implementation supports a refresh request sent from\nthe server to the client.\n\nNote that this event is global and will force the client to refresh all\npulled diagnostics currently shown. It should be used with absolute care and\nis useful for situation where a server for example detects a project wide\nchange that requires such a calculation." + } + ], + "documentation": "Workspace client capabilities specific to diagnostic pull requests.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TextDocumentSyncClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether text document synchronization supports dynamic registration." + }, + { + "name": "willSave", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports sending will save notifications." + }, + { + "name": "willSaveWaitUntil", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports sending a will save request and\nwaits for a response providing text edits which will\nbe applied to the document before it is saved." + }, + { + "name": "didSave", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports did save notifications." + } + ] + }, + { + "name": "CompletionClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether completion supports dynamic registration." + }, + { + "name": "completionItem", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "snippetSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports snippets as insert text.\n\nA snippet can define tab stops and placeholders with `$1`, `$2`\nand `${3:foo}`. `$0` defines the final tab stop, it defaults to\nthe end of the snippet. Placeholders with equal identifiers are linked,\nthat is typing in one will update others too." + }, + { + "name": "commitCharactersSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports commit characters on a completion item." + }, + { + "name": "documentationFormat", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "MarkupKind" + } + }, + "optional": true, + "documentation": "Client supports the following content formats for the documentation\nproperty. The order describes the preferred format of the client." + }, + { + "name": "deprecatedSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports the deprecated property on a completion item." + }, + { + "name": "preselectSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports the preselect property on a completion item." + }, + { + "name": "tagSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItemTag" + } + }, + "documentation": "The tags supported by the client." + } + ] + } + }, + "optional": true, + "documentation": "Client supports the tag property on a completion item. Clients supporting\ntags have to handle unknown tags gracefully. Clients especially need to\npreserve unknown tags when sending a completion item back to the server in\na resolve call.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "insertReplaceSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client support insert replace edit to control different behavior if a\ncompletion item is inserted in the text or should replace text.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "resolveSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "properties", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The properties that a client can resolve lazily." + } + ] + } + }, + "optional": true, + "documentation": "Indicates which properties a client can resolve lazily on a completion\nitem. Before version 3.16.0 only the predefined properties `documentation`\nand `details` could be resolved lazily.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "insertTextModeSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "InsertTextMode" + } + } + } + ] + } + }, + "optional": true, + "documentation": "The client supports the `insertTextMode` property on\na completion item to override the whitespace handling mode\nas defined by the client (see `insertTextMode`).\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "labelDetailsSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client has support for completion item label\ndetails (see also `CompletionItemLabelDetails`).\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + } + }, + "optional": true, + "documentation": "The client supports the following `CompletionItem` specific\ncapabilities." + }, + { + "name": "completionItemKind", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CompletionItemKind" + } + }, + "optional": true, + "documentation": "The completion item kind values the client supports. When this\nproperty exists the client also guarantees that it will\nhandle values outside its set gracefully and falls back\nto a default value when unknown.\n\nIf this property is not present the client only supports\nthe completion items kinds from `Text` to `Reference` as defined in\nthe initial version of the protocol." + } + ] + } + }, + "optional": true + }, + { + "name": "insertTextMode", + "type": { + "kind": "reference", + "name": "InsertTextMode" + }, + "optional": true, + "documentation": "Defines how the client handles whitespace and indentation\nwhen accepting a completion item that uses multi line\ntext in either `insertText` or `textEdit`.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "contextSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports to send additional context information for a\n`textDocument/completion` request." + }, + { + "name": "completionList", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "itemDefaults", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "The client supports the following itemDefaults on\na completion list.\n\nThe value lists the supported property names of the\n`CompletionList.itemDefaults` object. If omitted\nno properties are supported.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + } + }, + "optional": true, + "documentation": "The client supports the following `CompletionList` specific\ncapabilities.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Completion client capabilities" + }, + { + "name": "HoverClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether hover supports dynamic registration." + }, + { + "name": "contentFormat", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "MarkupKind" + } + }, + "optional": true, + "documentation": "Client supports the following content formats for the content\nproperty. The order describes the preferred format of the client." + } + ] + }, + { + "name": "SignatureHelpClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether signature help supports dynamic registration." + }, + { + "name": "signatureInformation", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "documentationFormat", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "MarkupKind" + } + }, + "optional": true, + "documentation": "Client supports the following content formats for the documentation\nproperty. The order describes the preferred format of the client." + }, + { + "name": "parameterInformation", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "labelOffsetSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports processing label offsets instead of a\nsimple label string.\n\n@since 3.14.0", + "since": "3.14.0" + } + ] + } + }, + "optional": true, + "documentation": "Client capabilities specific to parameter information." + }, + { + "name": "activeParameterSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports the `activeParameter` property on `SignatureInformation`\nliteral.\n\n@since 3.16.0", + "since": "3.16.0" + } + ] + } + }, + "optional": true, + "documentation": "The client supports the following `SignatureInformation`\nspecific properties." + }, + { + "name": "contextSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports to send additional context information for a\n`textDocument/signatureHelp` request. A client that opts into\ncontextSupport will also support the `retriggerCharacters` on\n`SignatureHelpOptions`.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "documentation": "Client Capabilities for a [SignatureHelpRequest](#SignatureHelpRequest)." + }, + { + "name": "DeclarationClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether declaration supports dynamic registration. If this is set to `true`\nthe client supports the new `DeclarationRegistrationOptions` return value\nfor the corresponding server capability as well." + }, + { + "name": "linkSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports additional metadata in the form of declaration links." + } + ], + "documentation": "@since 3.14.0", + "since": "3.14.0" + }, + { + "name": "DefinitionClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether definition supports dynamic registration." + }, + { + "name": "linkSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports additional metadata in the form of definition links.\n\n@since 3.14.0", + "since": "3.14.0" + } + ], + "documentation": "Client Capabilities for a [DefinitionRequest](#DefinitionRequest)." + }, + { + "name": "TypeDefinitionClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `TypeDefinitionRegistrationOptions` return value\nfor the corresponding server capability as well." + }, + { + "name": "linkSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports additional metadata in the form of definition links.\n\nSince 3.14.0" + } + ], + "documentation": "Since 3.6.0" + }, + { + "name": "ImplementationClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `ImplementationRegistrationOptions` return value\nfor the corresponding server capability as well." + }, + { + "name": "linkSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports additional metadata in the form of definition links.\n\n@since 3.14.0", + "since": "3.14.0" + } + ], + "documentation": "@since 3.6.0", + "since": "3.6.0" + }, + { + "name": "ReferenceClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether references supports dynamic registration." + } + ], + "documentation": "Client Capabilities for a [ReferencesRequest](#ReferencesRequest)." + }, + { + "name": "DocumentHighlightClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether document highlight supports dynamic registration." + } + ], + "documentation": "Client Capabilities for a [DocumentHighlightRequest](#DocumentHighlightRequest)." + }, + { + "name": "DocumentSymbolClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether document symbol supports dynamic registration." + }, + { + "name": "symbolKind", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolKind" + } + }, + "optional": true, + "documentation": "The symbol kind values the client supports. When this\nproperty exists the client also guarantees that it will\nhandle values outside its set gracefully and falls back\nto a default value when unknown.\n\nIf this property is not present the client only supports\nthe symbol kinds from `File` to `Array` as defined in\nthe initial version of the protocol." + } + ] + } + }, + "optional": true, + "documentation": "Specific capabilities for the `SymbolKind` in the\n`textDocument/documentSymbol` request." + }, + { + "name": "hierarchicalDocumentSymbolSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports hierarchical document symbols." + }, + { + "name": "tagSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "SymbolTag" + } + }, + "documentation": "The tags supported by the client." + } + ] + } + }, + "optional": true, + "documentation": "The client supports tags on `SymbolInformation`. Tags are supported on\n`DocumentSymbol` if `hierarchicalDocumentSymbolSupport` is set to true.\nClients supporting tags have to handle unknown tags gracefully.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "labelSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports an additional label presented in the UI when\nregistering a document symbol provider.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "Client Capabilities for a [DocumentSymbolRequest](#DocumentSymbolRequest)." + }, + { + "name": "CodeActionClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code action supports dynamic registration." + }, + { + "name": "codeActionLiteralSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "codeActionKind", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "CodeActionKind" + } + }, + "documentation": "The code action kind values the client supports. When this\nproperty exists the client also guarantees that it will\nhandle values outside its set gracefully and falls back\nto a default value when unknown." + } + ] + } + }, + "documentation": "The code action kind is support with the following value\nset." + } + ] + } + }, + "optional": true, + "documentation": "The client support code action literals of type `CodeAction` as a valid\nresponse of the `textDocument/codeAction` request. If the property is not\nset the request can only return `Command` literals.\n\n@since 3.8.0", + "since": "3.8.0" + }, + { + "name": "isPreferredSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code action supports the `isPreferred` property.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "disabledSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code action supports the `disabled` property.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "dataSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code action supports the `data` property which is\npreserved between a `textDocument/codeAction` and a\n`codeAction/resolve` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "resolveSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "properties", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The properties that a client can resolve lazily." + } + ] + } + }, + "optional": true, + "documentation": "Whether the client supports resolving additional code action\nproperties via a separate `codeAction/resolve` request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "honorsChangeAnnotations", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client honors the change annotations in\ntext edits and resource operations returned via the\n`CodeAction#edit` property by for example presenting\nthe workspace edit in the user interface and asking\nfor confirmation.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "The Client Capabilities of a [CodeActionRequest](#CodeActionRequest)." + }, + { + "name": "CodeLensClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code lens supports dynamic registration." + } + ], + "documentation": "The client capabilities of a [CodeLensRequest](#CodeLensRequest)." + }, + { + "name": "DocumentLinkClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether document link supports dynamic registration." + }, + { + "name": "tooltipSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client supports the `tooltip` property on `DocumentLink`.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "documentation": "The client capabilities of a [DocumentLinkRequest](#DocumentLinkRequest)." + }, + { + "name": "DocumentColorClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `DocumentColorRegistrationOptions` return value\nfor the corresponding server capability as well." + } + ] + }, + { + "name": "DocumentFormattingClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether formatting supports dynamic registration." + } + ], + "documentation": "Client capabilities of a [DocumentFormattingRequest](#DocumentFormattingRequest)." + }, + { + "name": "DocumentRangeFormattingClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether range formatting supports dynamic registration." + } + ], + "documentation": "Client capabilities of a [DocumentRangeFormattingRequest](#DocumentRangeFormattingRequest)." + }, + { + "name": "DocumentOnTypeFormattingClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether on type formatting supports dynamic registration." + } + ], + "documentation": "Client capabilities of a [DocumentOnTypeFormattingRequest](#DocumentOnTypeFormattingRequest)." + }, + { + "name": "RenameClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether rename supports dynamic registration." + }, + { + "name": "prepareSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports testing for validity of rename operations\nbefore execution.\n\n@since 3.12.0", + "since": "3.12.0" + }, + { + "name": "prepareSupportDefaultBehavior", + "type": { + "kind": "reference", + "name": "PrepareSupportDefaultBehavior" + }, + "optional": true, + "documentation": "Client supports the default behavior result.\n\nThe value indicates the default behavior used by the\nclient.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "honorsChangeAnnotations", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client honors the change annotations in\ntext edits and resource operations returned via the\nrename request's workspace edit by for example presenting\nthe workspace edit in the user interface and asking\nfor confirmation.\n\n@since 3.16.0", + "since": "3.16.0" + } + ] + }, + { + "name": "FoldingRangeClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration for folding range\nproviders. If this is set to `true` the client supports the new\n`FoldingRangeRegistrationOptions` return value for the corresponding\nserver capability as well." + }, + { + "name": "rangeLimit", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The maximum number of folding ranges that the client prefers to receive\nper document. The value serves as a hint, servers are free to follow the\nlimit." + }, + { + "name": "lineFoldingOnly", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "If set, the client signals that it only supports folding complete lines.\nIf set, client will ignore specified `startCharacter` and `endCharacter`\nproperties in a FoldingRange." + }, + { + "name": "foldingRangeKind", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "FoldingRangeKind" + } + }, + "optional": true, + "documentation": "The folding range kind values the client supports. When this\nproperty exists the client also guarantees that it will\nhandle values outside its set gracefully and falls back\nto a default value when unknown." + } + ] + } + }, + "optional": true, + "documentation": "Specific options for the folding range kind.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "foldingRange", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "collapsedText", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "If set, the client signals that it supports setting collapsedText on\nfolding ranges to display custom labels instead of the default text.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + } + }, + "optional": true, + "documentation": "Specific options for the folding range.\n\n@since 3.17.0", + "since": "3.17.0" + } + ] + }, + { + "name": "SelectionRangeClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration for selection range providers. If this is set to `true`\nthe client supports the new `SelectionRangeRegistrationOptions` return value for the corresponding server\ncapability as well." + } + ] + }, + { + "name": "PublishDiagnosticsClientCapabilities", + "properties": [ + { + "name": "relatedInformation", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the clients accepts diagnostics with related information." + }, + { + "name": "tagSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "valueSet", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DiagnosticTag" + } + }, + "documentation": "The tags supported by the client." + } + ] + } + }, + "optional": true, + "documentation": "Client supports the tag property to provide meta data about a diagnostic.\nClients supporting tags have to handle unknown tags gracefully.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "versionSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client interprets the version property of the\n`textDocument/publishDiagnostics` notification's parameter.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "codeDescriptionSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Client supports a codeDescription property\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "dataSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether code action supports the `data` property which is\npreserved between a `textDocument/publishDiagnostics` and\n`textDocument/codeAction` request.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "documentation": "The publish diagnostic client capabilities." + }, + { + "name": "CallHierarchyClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokensClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + }, + { + "name": "requests", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "range", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "literal", + "value": { + "properties": [] + } + } + ] + }, + "optional": true, + "documentation": "The client will send the `textDocument/semanticTokens/range` request if\nthe server provides a corresponding handler." + }, + { + "name": "full", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "delta", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client will send the `textDocument/semanticTokens/full/delta` request if\nthe server provides a corresponding handler." + } + ] + } + } + ] + }, + "optional": true, + "documentation": "The client will send the `textDocument/semanticTokens/full` request if\nthe server provides a corresponding handler." + } + ] + } + }, + "documentation": "Which requests the client supports and might send to the server\ndepending on the server's capability. Please note that clients might not\nshow semantic tokens or degrade some of the user experience if a range\nor full request is advertised by the client but not provided by the\nserver. If for example the client capability `requests.full` and\n`request.range` are both set to true but the server only provides a\nrange provider the client might not render a minimap correctly or might\neven decide to not show any semantic tokens at all." + }, + { + "name": "tokenTypes", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The token types that the client supports." + }, + { + "name": "tokenModifiers", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The token modifiers that the client supports." + }, + { + "name": "formats", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "TokenFormat" + } + }, + "documentation": "The token formats the clients supports." + }, + { + "name": "overlappingTokenSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client supports tokens that can overlap each other." + }, + { + "name": "multilineTokenSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client supports tokens that can span multiple lines." + }, + { + "name": "serverCancelSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client allows the server to actively cancel a\nsemantic token request, e.g. supports returning\nLSPErrorCodes.ServerCancelled. If a server does the client\nneeds to retrigger the request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "augmentsSyntaxTokens", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client uses semantic tokens to augment existing\nsyntax tokens. If set to `true` client side created syntax\ntokens and semantic tokens are both used for colorization. If\nset to `false` the client only uses the returned semantic tokens\nfor colorization.\n\nIf the value is `undefined` then the client behavior is not\nspecified.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "LinkedEditingRangeClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + } + ], + "documentation": "Client capabilities for the linked editing range request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MonikerClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether moniker supports dynamic registration. If this is set to `true`\nthe client supports the new `MonikerRegistrationOptions` return value\nfor the corresponding server capability as well." + } + ], + "documentation": "Client capabilities specific to the moniker request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "TypeHierarchyClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + } + ], + "documentation": "@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlineValueClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration for inline value providers." + } + ], + "documentation": "Client capabilities specific to inline values.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "InlayHintClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether inlay hints support dynamic registration." + }, + { + "name": "resolveSupport", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "properties", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "documentation": "The properties that a client can resolve lazily." + } + ] + } + }, + "optional": true, + "documentation": "Indicates which properties a client can resolve lazily on an inlay\nhint." + } + ], + "documentation": "Inlay hint client capabilities.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DiagnosticClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is set to `true`\nthe client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + }, + { + "name": "relatedDocumentSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the clients supports related documents for document diagnostic pulls." + } + ], + "documentation": "Client capabilities specific to diagnostic pull requests.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocumentSyncClientCapabilities", + "properties": [ + { + "name": "dynamicRegistration", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether implementation supports dynamic registration. If this is\nset to `true` the client supports the new\n`(TextDocumentRegistrationOptions & StaticRegistrationOptions)`\nreturn value for the corresponding server capability as well." + }, + { + "name": "executionSummarySupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "The client supports sending execution summary data per cell." + } + ], + "documentation": "Notebook specific client capabilities.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ShowMessageRequestClientCapabilities", + "properties": [ + { + "name": "messageActionItem", + "type": { + "kind": "literal", + "value": { + "properties": [ + { + "name": "additionalPropertiesSupport", + "type": { + "kind": "base", + "name": "boolean" + }, + "optional": true, + "documentation": "Whether the client supports additional attributes which\nare preserved and send back to the server in the\nrequest's response." + } + ] + } + }, + "optional": true, + "documentation": "Capabilities specific to the `MessageActionItem` type." + } + ], + "documentation": "Show message request client capabilities" + }, + { + "name": "ShowDocumentClientCapabilities", + "properties": [ + { + "name": "support", + "type": { + "kind": "base", + "name": "boolean" + }, + "documentation": "The client has support for the showDocument\nrequest." + } + ], + "documentation": "Client capabilities for the showDocument request.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "RegularExpressionsClientCapabilities", + "properties": [ + { + "name": "engine", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The engine's name." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The engine's version." + } + ], + "documentation": "Client capabilities specific to regular expressions.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MarkdownClientCapabilities", + "properties": [ + { + "name": "parser", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The name of the parser." + }, + { + "name": "version", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The version of the parser." + }, + { + "name": "allowedTags", + "type": { + "kind": "array", + "element": { + "kind": "base", + "name": "string" + } + }, + "optional": true, + "documentation": "A list of HTML tags that the client allows / supports in\nMarkdown.\n\n@since 3.17.0", + "since": "3.17.0" + } + ], + "documentation": "Client capabilities specific to the used markdown parser.\n\n@since 3.16.0", + "since": "3.16.0" + } + ], + "enumerations": [ + { + "name": "SemanticTokenTypes", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "namespace", + "value": "namespace" + }, + { + "name": "type", + "value": "type", + "documentation": "Represents a generic type. Acts as a fallback for types which can't be mapped to\na specific type like class or enum." + }, + { + "name": "class", + "value": "class" + }, + { + "name": "enum", + "value": "enum" + }, + { + "name": "interface", + "value": "interface" + }, + { + "name": "struct", + "value": "struct" + }, + { + "name": "typeParameter", + "value": "typeParameter" + }, + { + "name": "parameter", + "value": "parameter" + }, + { + "name": "variable", + "value": "variable" + }, + { + "name": "property", + "value": "property" + }, + { + "name": "enumMember", + "value": "enumMember" + }, + { + "name": "event", + "value": "event" + }, + { + "name": "function", + "value": "function" + }, + { + "name": "method", + "value": "method" + }, + { + "name": "macro", + "value": "macro" + }, + { + "name": "keyword", + "value": "keyword" + }, + { + "name": "modifier", + "value": "modifier" + }, + { + "name": "comment", + "value": "comment" + }, + { + "name": "string", + "value": "string" + }, + { + "name": "number", + "value": "number" + }, + { + "name": "regexp", + "value": "regexp" + }, + { + "name": "operator", + "value": "operator" + }, + { + "name": "decorator", + "value": "decorator", + "documentation": "@since 3.17.0", + "since": "3.17.0" + } + ], + "supportsCustomValues": true, + "documentation": "A set of predefined token types. This set is not fixed\nan clients can specify additional token types via the\ncorresponding client capabilities.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "SemanticTokenModifiers", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "declaration", + "value": "declaration" + }, + { + "name": "definition", + "value": "definition" + }, + { + "name": "readonly", + "value": "readonly" + }, + { + "name": "static", + "value": "static" + }, + { + "name": "deprecated", + "value": "deprecated" + }, + { + "name": "abstract", + "value": "abstract" + }, + { + "name": "async", + "value": "async" + }, + { + "name": "modification", + "value": "modification" + }, + { + "name": "documentation", + "value": "documentation" + }, + { + "name": "defaultLibrary", + "value": "defaultLibrary" + } + ], + "supportsCustomValues": true, + "documentation": "A set of predefined token modifiers. This set is not fixed\nan clients can specify additional token types via the\ncorresponding client capabilities.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "DocumentDiagnosticReportKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Full", + "value": "full", + "documentation": "A diagnostic report with a full\nset of problems." + }, + { + "name": "Unchanged", + "value": "unchanged", + "documentation": "A report indicating that the last\nreturned report is still accurate." + } + ], + "documentation": "The document diagnostic report kinds.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ErrorCodes", + "type": { + "kind": "base", + "name": "integer" + }, + "values": [ + { + "name": "ParseError", + "value": -32700 + }, + { + "name": "InvalidRequest", + "value": -32600 + }, + { + "name": "MethodNotFound", + "value": -32601 + }, + { + "name": "InvalidParams", + "value": -32602 + }, + { + "name": "InternalError", + "value": -32603 + }, + { + "name": "ServerNotInitialized", + "value": -32002, + "documentation": "Error code indicating that a server received a notification or\nrequest before the server has received the `initialize` request." + }, + { + "name": "UnknownErrorCode", + "value": -32001 + } + ], + "supportsCustomValues": true, + "documentation": "Predefined error codes." + }, + { + "name": "LSPErrorCodes", + "type": { + "kind": "base", + "name": "integer" + }, + "values": [ + { + "name": "RequestFailed", + "value": -32803, + "documentation": "A request failed but it was syntactically correct, e.g the\nmethod name was known and the parameters were valid. The error\nmessage should contain human readable information about why\nthe request failed.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ServerCancelled", + "value": -32802, + "documentation": "The server cancelled the request. This error code should\nonly be used for requests that explicitly support being\nserver cancellable.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ContentModified", + "value": -32801, + "documentation": "The server detected that the content of a document got\nmodified outside normal conditions. A server should\nNOT send this error code if it detects a content change\nin it unprocessed messages. The result even computed\non an older state might still be useful for the client.\n\nIf a client decides that a result is not of any use anymore\nthe client should cancel the request." + }, + { + "name": "RequestCancelled", + "value": -32800, + "documentation": "The client has canceled a request and a server as detected\nthe cancel." + } + ], + "supportsCustomValues": true + }, + { + "name": "FoldingRangeKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Comment", + "value": "comment", + "documentation": "Folding range for a comment" + }, + { + "name": "Imports", + "value": "imports", + "documentation": "Folding range for an import or include" + }, + { + "name": "Region", + "value": "region", + "documentation": "Folding range for a region (e.g. `#region`)" + } + ], + "supportsCustomValues": true, + "documentation": "A set of predefined range kinds." + }, + { + "name": "SymbolKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "File", + "value": 1 + }, + { + "name": "Module", + "value": 2 + }, + { + "name": "Namespace", + "value": 3 + }, + { + "name": "Package", + "value": 4 + }, + { + "name": "Class", + "value": 5 + }, + { + "name": "Method", + "value": 6 + }, + { + "name": "Property", + "value": 7 + }, + { + "name": "Field", + "value": 8 + }, + { + "name": "Constructor", + "value": 9 + }, + { + "name": "Enum", + "value": 10 + }, + { + "name": "Interface", + "value": 11 + }, + { + "name": "Function", + "value": 12 + }, + { + "name": "Variable", + "value": 13 + }, + { + "name": "Constant", + "value": 14 + }, + { + "name": "String", + "value": 15 + }, + { + "name": "Number", + "value": 16 + }, + { + "name": "Boolean", + "value": 17 + }, + { + "name": "Array", + "value": 18 + }, + { + "name": "Object", + "value": 19 + }, + { + "name": "Key", + "value": 20 + }, + { + "name": "Null", + "value": 21 + }, + { + "name": "EnumMember", + "value": 22 + }, + { + "name": "Struct", + "value": 23 + }, + { + "name": "Event", + "value": 24 + }, + { + "name": "Operator", + "value": 25 + }, + { + "name": "TypeParameter", + "value": 26 + } + ], + "documentation": "A symbol kind." + }, + { + "name": "SymbolTag", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Deprecated", + "value": 1, + "documentation": "Render a symbol as obsolete, usually using a strike-out." + } + ], + "documentation": "Symbol tags are extra annotations that tweak the rendering of a symbol.\n\n@since 3.16", + "since": "3.16" + }, + { + "name": "UniquenessLevel", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "document", + "value": "document", + "documentation": "The moniker is only unique inside a document" + }, + { + "name": "project", + "value": "project", + "documentation": "The moniker is unique inside a project for which a dump got created" + }, + { + "name": "group", + "value": "group", + "documentation": "The moniker is unique inside the group to which a project belongs" + }, + { + "name": "scheme", + "value": "scheme", + "documentation": "The moniker is unique inside the moniker scheme." + }, + { + "name": "global", + "value": "global", + "documentation": "The moniker is globally unique" + } + ], + "documentation": "Moniker uniqueness level to define scope of the moniker.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "MonikerKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "import", + "value": "import", + "documentation": "The moniker represent a symbol that is imported into a project" + }, + { + "name": "export", + "value": "export", + "documentation": "The moniker represents a symbol that is exported from a project" + }, + { + "name": "local", + "value": "local", + "documentation": "The moniker represents a symbol that is local to a project (e.g. a local\nvariable of a function, a class not visible outside the project, ...)" + } + ], + "documentation": "The moniker kind.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "InlayHintKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Type", + "value": 1, + "documentation": "An inlay hint that for a type annotation." + }, + { + "name": "Parameter", + "value": 2, + "documentation": "An inlay hint that is for a parameter." + } + ], + "documentation": "Inlay hint kinds.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "MessageType", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Error", + "value": 1, + "documentation": "An error message." + }, + { + "name": "Warning", + "value": 2, + "documentation": "A warning message." + }, + { + "name": "Info", + "value": 3, + "documentation": "An information message." + }, + { + "name": "Log", + "value": 4, + "documentation": "A log message." + } + ], + "documentation": "The message type" + }, + { + "name": "TextDocumentSyncKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "None", + "value": 0, + "documentation": "Documents should not be synced at all." + }, + { + "name": "Full", + "value": 1, + "documentation": "Documents are synced by always sending the full content\nof the document." + }, + { + "name": "Incremental", + "value": 2, + "documentation": "Documents are synced by sending the full content on open.\nAfter that only incremental updates to the document are\nsend." + } + ], + "documentation": "Defines how the host (editor) should sync\ndocument changes to the language server." + }, + { + "name": "TextDocumentSaveReason", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Manual", + "value": 1, + "documentation": "Manually triggered, e.g. by the user pressing save, by starting debugging,\nor by an API call." + }, + { + "name": "AfterDelay", + "value": 2, + "documentation": "Automatic after a delay." + }, + { + "name": "FocusOut", + "value": 3, + "documentation": "When the editor lost focus." + } + ], + "documentation": "Represents reasons why a text document is saved." + }, + { + "name": "CompletionItemKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Text", + "value": 1 + }, + { + "name": "Method", + "value": 2 + }, + { + "name": "Function", + "value": 3 + }, + { + "name": "Constructor", + "value": 4 + }, + { + "name": "Field", + "value": 5 + }, + { + "name": "Variable", + "value": 6 + }, + { + "name": "Class", + "value": 7 + }, + { + "name": "Interface", + "value": 8 + }, + { + "name": "Module", + "value": 9 + }, + { + "name": "Property", + "value": 10 + }, + { + "name": "Unit", + "value": 11 + }, + { + "name": "Value", + "value": 12 + }, + { + "name": "Enum", + "value": 13 + }, + { + "name": "Keyword", + "value": 14 + }, + { + "name": "Snippet", + "value": 15 + }, + { + "name": "Color", + "value": 16 + }, + { + "name": "File", + "value": 17 + }, + { + "name": "Reference", + "value": 18 + }, + { + "name": "Folder", + "value": 19 + }, + { + "name": "EnumMember", + "value": 20 + }, + { + "name": "Constant", + "value": 21 + }, + { + "name": "Struct", + "value": 22 + }, + { + "name": "Event", + "value": 23 + }, + { + "name": "Operator", + "value": 24 + }, + { + "name": "TypeParameter", + "value": 25 + } + ], + "documentation": "The kind of a completion entry." + }, + { + "name": "CompletionItemTag", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Deprecated", + "value": 1, + "documentation": "Render a completion as obsolete, usually using a strike-out." + } + ], + "documentation": "Completion item tags are extra annotations that tweak the rendering of a completion\nitem.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "InsertTextFormat", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "PlainText", + "value": 1, + "documentation": "The primary text to be inserted is treated as a plain string." + }, + { + "name": "Snippet", + "value": 2, + "documentation": "The primary text to be inserted is treated as a snippet.\n\nA snippet can define tab stops and placeholders with `$1`, `$2`\nand `${3:foo}`. `$0` defines the final tab stop, it defaults to\nthe end of the snippet. Placeholders with equal identifiers are linked,\nthat is typing in one will update others too.\n\nSee also: https://microsoft.github.io/language-server-protocol/specifications/specification-current/#snippet_syntax" + } + ], + "documentation": "Defines whether the insert text in a completion item should be interpreted as\nplain text or a snippet." + }, + { + "name": "InsertTextMode", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "asIs", + "value": 1, + "documentation": "The insertion or replace strings is taken as it is. If the\nvalue is multi line the lines below the cursor will be\ninserted using the indentation defined in the string value.\nThe client will not apply any kind of adjustments to the\nstring." + }, + { + "name": "adjustIndentation", + "value": 2, + "documentation": "The editor adjusts leading whitespace of new lines so that\nthey match the indentation up to the cursor of the line for\nwhich the item is accepted.\n\nConsider a line like this: <2tabs><3tabs>foo. Accepting a\nmulti line completion item is indented using 2 tabs and all\nfollowing lines inserted will be indented using 2 tabs as well." + } + ], + "documentation": "How whitespace and indentation is handled during completion\nitem insertion.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "DocumentHighlightKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Text", + "value": 1, + "documentation": "A textual occurrence." + }, + { + "name": "Read", + "value": 2, + "documentation": "Read-access of a symbol, like reading a variable." + }, + { + "name": "Write", + "value": 3, + "documentation": "Write-access of a symbol, like writing to a variable." + } + ], + "documentation": "A document highlight kind." + }, + { + "name": "CodeActionKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Empty", + "value": "", + "documentation": "Empty kind." + }, + { + "name": "QuickFix", + "value": "quickfix", + "documentation": "Base kind for quickfix actions: 'quickfix'" + }, + { + "name": "Refactor", + "value": "refactor", + "documentation": "Base kind for refactoring actions: 'refactor'" + }, + { + "name": "RefactorExtract", + "value": "refactor.extract", + "documentation": "Base kind for refactoring extraction actions: 'refactor.extract'\n\nExample extract actions:\n\n- Extract method\n- Extract function\n- Extract variable\n- Extract interface from class\n- ..." + }, + { + "name": "RefactorInline", + "value": "refactor.inline", + "documentation": "Base kind for refactoring inline actions: 'refactor.inline'\n\nExample inline actions:\n\n- Inline function\n- Inline variable\n- Inline constant\n- ..." + }, + { + "name": "RefactorRewrite", + "value": "refactor.rewrite", + "documentation": "Base kind for refactoring rewrite actions: 'refactor.rewrite'\n\nExample rewrite actions:\n\n- Convert JavaScript function to class\n- Add or remove parameter\n- Encapsulate field\n- Make method static\n- Move method to base class\n- ..." + }, + { + "name": "Source", + "value": "source", + "documentation": "Base kind for source actions: `source`\n\nSource code actions apply to the entire file." + }, + { + "name": "SourceOrganizeImports", + "value": "source.organizeImports", + "documentation": "Base kind for an organize imports source action: `source.organizeImports`" + }, + { + "name": "SourceFixAll", + "value": "source.fixAll", + "documentation": "Base kind for auto-fix source actions: `source.fixAll`.\n\nFix all actions automatically fix errors that have a clear fix that do not require user input.\nThey should not suppress errors or perform unsafe fixes such as generating new types or classes.\n\n@since 3.15.0", + "since": "3.15.0" + } + ], + "supportsCustomValues": true, + "documentation": "A set of predefined code action kinds" + }, + { + "name": "TraceValues", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Off", + "value": "off", + "documentation": "Turn tracing off." + }, + { + "name": "Messages", + "value": "messages", + "documentation": "Trace messages only." + }, + { + "name": "Verbose", + "value": "verbose", + "documentation": "Verbose message tracing." + } + ] + }, + { + "name": "MarkupKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "PlainText", + "value": "plaintext", + "documentation": "Plain text is supported as a content format" + }, + { + "name": "Markdown", + "value": "markdown", + "documentation": "Markdown is supported as a content format" + } + ], + "documentation": "Describes the content type that a client supports in various\nresult literals like `Hover`, `ParameterInfo` or `CompletionItem`.\n\nPlease note that `MarkupKinds` must not start with a `$`. This kinds\nare reserved for internal usage." + }, + { + "name": "PositionEncodingKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "UTF8", + "value": "utf-8", + "documentation": "Character offsets count UTF-8 code units." + }, + { + "name": "UTF16", + "value": "utf-16", + "documentation": "Character offsets count UTF-16 code units.\n\nThis is the default and must always be supported\nby servers" + }, + { + "name": "UTF32", + "value": "utf-32", + "documentation": "Character offsets count UTF-32 code units.\n\nImplementation note: these are the same as Unicode code points,\nso this `PositionEncodingKind` may also be used for an\nencoding-agnostic representation of character offsets." + } + ], + "supportsCustomValues": true, + "documentation": "A set of predefined position encoding kinds.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "FileChangeType", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Created", + "value": 1, + "documentation": "The file got created." + }, + { + "name": "Changed", + "value": 2, + "documentation": "The file got changed." + }, + { + "name": "Deleted", + "value": 3, + "documentation": "The file got deleted." + } + ], + "documentation": "The file event type" + }, + { + "name": "WatchKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Create", + "value": 1, + "documentation": "Interested in create events." + }, + { + "name": "Change", + "value": 2, + "documentation": "Interested in change events" + }, + { + "name": "Delete", + "value": 4, + "documentation": "Interested in delete events" + } + ], + "supportsCustomValues": true + }, + { + "name": "DiagnosticSeverity", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Error", + "value": 1, + "documentation": "Reports an error." + }, + { + "name": "Warning", + "value": 2, + "documentation": "Reports a warning." + }, + { + "name": "Information", + "value": 3, + "documentation": "Reports an information." + }, + { + "name": "Hint", + "value": 4, + "documentation": "Reports a hint." + } + ], + "documentation": "The diagnostic's severity." + }, + { + "name": "DiagnosticTag", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Unnecessary", + "value": 1, + "documentation": "Unused or unnecessary code.\n\nClients are allowed to render diagnostics with this tag faded out instead of having\nan error squiggle." + }, + { + "name": "Deprecated", + "value": 2, + "documentation": "Deprecated or obsolete code.\n\nClients are allowed to rendered diagnostics with this tag strike through." + } + ], + "documentation": "The diagnostic tags.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "CompletionTriggerKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Invoked", + "value": 1, + "documentation": "Completion was triggered by typing an identifier (24x7 code\ncomplete), manual invocation (e.g Ctrl+Space) or via API." + }, + { + "name": "TriggerCharacter", + "value": 2, + "documentation": "Completion was triggered by a trigger character specified by\nthe `triggerCharacters` properties of the `CompletionRegistrationOptions`." + }, + { + "name": "TriggerForIncompleteCompletions", + "value": 3, + "documentation": "Completion was re-triggered as current completion list is incomplete" + } + ], + "documentation": "How a completion was triggered" + }, + { + "name": "SignatureHelpTriggerKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Invoked", + "value": 1, + "documentation": "Signature help was invoked manually by the user or by a command." + }, + { + "name": "TriggerCharacter", + "value": 2, + "documentation": "Signature help was triggered by a trigger character." + }, + { + "name": "ContentChange", + "value": 3, + "documentation": "Signature help was triggered by the cursor moving or by the document content changing." + } + ], + "documentation": "How a signature help was triggered.\n\n@since 3.15.0", + "since": "3.15.0" + }, + { + "name": "CodeActionTriggerKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Invoked", + "value": 1, + "documentation": "Code actions were explicitly requested by the user or by an extension." + }, + { + "name": "Automatic", + "value": 2, + "documentation": "Code actions were requested automatically.\n\nThis typically happens when current selection in a file changes, but can\nalso be triggered when file content changes." + } + ], + "documentation": "The reason why code actions were requested.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "FileOperationPatternKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "file", + "value": "file", + "documentation": "The pattern matches a file only." + }, + { + "name": "folder", + "value": "folder", + "documentation": "The pattern matches a folder only." + } + ], + "documentation": "A pattern kind describing if a glob pattern matches a file a folder or\nboth.\n\n@since 3.16.0", + "since": "3.16.0" + }, + { + "name": "NotebookCellKind", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Markup", + "value": 1, + "documentation": "A markup-cell is formatted source that is used for display." + }, + { + "name": "Code", + "value": 2, + "documentation": "A code-cell is source code." + } + ], + "documentation": "A notebook cell kind.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "ResourceOperationKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Create", + "value": "create", + "documentation": "Supports creating new files and folders." + }, + { + "name": "Rename", + "value": "rename", + "documentation": "Supports renaming existing files and folders." + }, + { + "name": "Delete", + "value": "delete", + "documentation": "Supports deleting existing files and folders." + } + ] + }, + { + "name": "FailureHandlingKind", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Abort", + "value": "abort", + "documentation": "Applying the workspace change is simply aborted if one of the changes provided\nfails. All operations executed before the failing operation stay executed." + }, + { + "name": "Transactional", + "value": "transactional", + "documentation": "All operations are executed transactional. That means they either all\nsucceed or no changes at all are applied to the workspace." + }, + { + "name": "TextOnlyTransactional", + "value": "textOnlyTransactional", + "documentation": "If the workspace edit contains only textual file changes they are executed transactional.\nIf resource changes (create, rename or delete file) are part of the change the failure\nhandling strategy is abort." + }, + { + "name": "Undo", + "value": "undo", + "documentation": "The client tries to undo the operations already executed. But there is no\nguarantee that this is succeeding." + } + ] + }, + { + "name": "PrepareSupportDefaultBehavior", + "type": { + "kind": "base", + "name": "uinteger" + }, + "values": [ + { + "name": "Identifier", + "value": 1, + "documentation": "The client's default behavior is to select the identifier\naccording the to language's syntax rule." + } + ] + }, + { + "name": "TokenFormat", + "type": { + "kind": "base", + "name": "string" + }, + "values": [ + { + "name": "Relative", + "value": "relative" + } + ] + } + ], + "typeAliases": [ + { + "name": "Definition", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Location" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + } + ] + }, + "documentation": "The definition of a symbol represented as one or many [locations](#Location).\nFor most programming languages there is only one location at which a symbol is\ndefined.\n\nServers should prefer returning `DefinitionLink` over `Definition` if supported\nby the client." + }, + { + "name": "DefinitionLink", + "type": { + "kind": "reference", + "name": "LocationLink" + }, + "documentation": "Information about where a symbol is defined.\n\nProvides additional metadata over normal [location](#Location) definitions, including the range of\nthe defining symbol" + }, + { + "name": "LSPArray", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "LSPAny" + } + }, + "documentation": "LSP arrays.\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "LSPAny", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "LSPObject" + }, + { + "kind": "reference", + "name": "LSPArray" + }, + { + "kind": "base", + "name": "string" + }, + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "uinteger" + }, + { + "kind": "base", + "name": "decimal" + }, + { + "kind": "base", + "name": "boolean" + }, + { + "kind": "base", + "name": "null" + } + ] + }, + "documentation": "The LSP any type.\nPlease note that strictly speaking a property with the value `undefined`\ncan't be converted into JSON preserving the property name. However for\nconvenience it is allowed and assumed that all these properties are\noptional as well.\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "Declaration", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Location" + }, + { + "kind": "array", + "element": { + "kind": "reference", + "name": "Location" + } + } + ] + }, + "documentation": "The declaration of a symbol representation as one or many [locations](#Location)." + }, + { + "name": "DeclarationLink", + "type": { + "kind": "reference", + "name": "LocationLink" + }, + "documentation": "Information about where a symbol is declared.\n\nProvides additional metadata over normal [location](#Location) declarations, including the range of\nthe declaring symbol.\n\nServers should prefer returning `DeclarationLink` over `Declaration` if supported\nby the client." + }, + { + "name": "InlineValue", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "InlineValueText" + }, + { + "kind": "reference", + "name": "InlineValueVariableLookup" + }, + { + "kind": "reference", + "name": "InlineValueEvaluatableExpression" + } + ] + }, + "documentation": "Inline value information can be provided by different means:\n- directly as a text value (class InlineValueText).\n- as a name to use for a variable lookup (class InlineValueVariableLookup)\n- as an evaluatable expression (class InlineValueEvaluatableExpression)\nThe InlineValue types combines all inline value types into one type.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "DocumentDiagnosticReport", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "RelatedFullDocumentDiagnosticReport" + }, + { + "kind": "reference", + "name": "RelatedUnchangedDocumentDiagnosticReport" + } + ] + }, + "documentation": "The result of a document diagnostic pull request. A report can\neither be a full report containing all diagnostics for the\nrequested document or an unchanged report indicating that nothing\nhas changed in terms of diagnostics in comparison to the last\npull request.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "PrepareRenameResult", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Range" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + } + }, + { + "name": "placeholder", + "type": { + "kind": "base", + "name": "string" + } + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "defaultBehavior", + "type": { + "kind": "base", + "name": "boolean" + } + } + ] + } + } + ] + } + }, + { + "name": "ProgressToken", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "integer" + }, + { + "kind": "base", + "name": "string" + } + ] + } + }, + { + "name": "DocumentSelector", + "type": { + "kind": "array", + "element": { + "kind": "reference", + "name": "DocumentFilter" + } + }, + "documentation": "A document selector is the combination of one or many document filters.\n\n@sample `let sel:DocumentSelector = [{ language: 'typescript' }, { language: 'json', pattern: '**∕tsconfig.json' }]`;\n\nThe use of a string as a document filter is deprecated @since 3.16.0.", + "since": "3.16.0." + }, + { + "name": "ChangeAnnotationIdentifier", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "An identifier to refer to a change annotation stored with a workspace edit." + }, + { + "name": "WorkspaceDocumentDiagnosticReport", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "WorkspaceFullDocumentDiagnosticReport" + }, + { + "kind": "reference", + "name": "WorkspaceUnchangedDocumentDiagnosticReport" + } + ] + }, + "documentation": "A workspace diagnostic document report.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TextDocumentContentChangeEvent", + "type": { + "kind": "or", + "items": [ + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "range", + "type": { + "kind": "reference", + "name": "Range" + }, + "documentation": "The range of the document that changed." + }, + { + "name": "rangeLength", + "type": { + "kind": "base", + "name": "uinteger" + }, + "optional": true, + "documentation": "The optional length of the range that got replaced.\n\n@deprecated use range instead." + }, + { + "name": "text", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The new text for the provided range." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "text", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The new text of the whole document." + } + ] + } + } + ] + }, + "documentation": "An event describing a change to a text document. If only a text is provided\nit is considered to be the full content of the document." + }, + { + "name": "MarkedString", + "type": { + "kind": "or", + "items": [ + { + "kind": "base", + "name": "string" + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + } + }, + { + "name": "value", + "type": { + "kind": "base", + "name": "string" + } + } + ] + } + } + ] + }, + "documentation": "MarkedString can be used to render human readable text. It is either a markdown string\nor a code-block that provides a language and a code snippet. The language identifier\nis semantically equal to the optional language identifier in fenced code blocks in GitHub\nissues. See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting\n\nThe pair of a language and a value is an equivalent to markdown:\n```${language}\n${value}\n```\n\nNote that markdown strings will be sanitized - that means html will be escaped.\n@deprecated use MarkupContent instead." + }, + { + "name": "DocumentFilter", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "TextDocumentFilter" + }, + { + "kind": "reference", + "name": "NotebookCellTextDocumentFilter" + } + ] + }, + "documentation": "A document filter describes a top level text document or\na notebook cell document.\n\n@since 3.17.0 - proposed support for NotebookCellTextDocumentFilter.", + "since": "3.17.0 - proposed support for NotebookCellTextDocumentFilter." + }, + { + "name": "GlobPattern", + "type": { + "kind": "or", + "items": [ + { + "kind": "reference", + "name": "Pattern" + }, + { + "kind": "reference", + "name": "RelativePattern" + } + ] + }, + "documentation": "The glob pattern. Either a string pattern or a relative pattern.\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "TextDocumentFilter", + "type": { + "kind": "or", + "items": [ + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A language id, like `typescript`." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A glob pattern, like `*.{ts,js}`." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A language id, like `typescript`." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A glob pattern, like `*.{ts,js}`." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "language", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A language id, like `typescript`." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A glob pattern, like `*.{ts,js}`." + } + ] + } + } + ] + }, + "documentation": "A document filter denotes a document by different properties like\nthe [language](#TextDocument.languageId), the [scheme](#Uri.scheme) of\nits resource, or a glob-pattern that is applied to the [path](#TextDocument.fileName).\n\nGlob patterns can have the following syntax:\n- `*` to match one or more characters in a path segment\n- `?` to match on one character in a path segment\n- `**` to match any number of path segments, including none\n- `{}` to group sub patterns into an OR expression. (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files)\n- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\n@sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`\n@sample A language filter that applies to all package.json paths: `{ language: 'json', pattern: '**package.json' }`\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "NotebookDocumentFilter", + "type": { + "kind": "or", + "items": [ + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "notebookType", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The type of the enclosing notebook." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A glob pattern." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "notebookType", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The type of the enclosing notebook." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A glob pattern." + } + ] + } + }, + { + "kind": "literal", + "value": { + "properties": [ + { + "name": "notebookType", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "The type of the enclosing notebook." + }, + { + "name": "scheme", + "type": { + "kind": "base", + "name": "string" + }, + "optional": true, + "documentation": "A Uri [scheme](#Uri.scheme), like `file` or `untitled`." + }, + { + "name": "pattern", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "A glob pattern." + } + ] + } + } + ] + }, + "documentation": "A notebook document filter denotes a notebook document by\ndifferent properties. The properties will be match\nagainst the notebook's URI (same as with documents)\n\n@since 3.17.0", + "since": "3.17.0" + }, + { + "name": "Pattern", + "type": { + "kind": "base", + "name": "string" + }, + "documentation": "The glob pattern to watch relative to the base path. Glob patterns can have the following syntax:\n- `*` to match one or more characters in a path segment\n- `?` to match on one character in a path segment\n- `**` to match any number of path segments, including none\n- `{}` to group conditions (e.g. `**​/*.{ts,js}` matches all TypeScript and JavaScript files)\n- `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)\n- `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)\n\n@since 3.17.0", + "since": "3.17.0" + } + ] +} diff --git a/lsp-types/src/Data/IxMap.hs b/lsp-types/src/Data/IxMap.hs index 760313c68..9d83acc02 100644 --- a/lsp-types/src/Data/IxMap.hs +++ b/lsp-types/src/Data/IxMap.hs @@ -1,16 +1,16 @@ +{-# LANGUAGE BangPatterns #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeInType #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} -{-# LANGUAGE BangPatterns #-} module Data.IxMap where +import Data.Kind import qualified Data.Map.Strict as M -import Data.Some -import Data.Kind -import Unsafe.Coerce +import Data.Some +import Unsafe.Coerce -- a `compare` b <=> toBase a `compare` toBase b -- toBase (i :: f a) == toBase (j :: f b) <=> a ~ b @@ -22,7 +22,7 @@ newtype IxMap (k :: a -> Type) (f :: a -> Type) = IxMap { getMap :: M.Map (Base emptyIxMap :: IxMap k f emptyIxMap = IxMap M.empty - + insertIxMap :: IxOrd k => k m -> f m -> IxMap k f -> Maybe (IxMap k f) insertIxMap (toBase -> i) x (IxMap m) | M.notMember i m = Just $ IxMap $ M.insert i (mkSome x) m @@ -32,10 +32,10 @@ lookupIxMap :: IxOrd k => k m -> IxMap k f -> Maybe (f m) lookupIxMap i (IxMap m) = case M.lookup (toBase i) m of Just (Some v) -> Just $ unsafeCoerce v - Nothing -> Nothing + Nothing -> Nothing pickFromIxMap :: IxOrd k => k m -> IxMap k f -> (Maybe (f m), IxMap k f) pickFromIxMap i (IxMap m) = case M.updateLookupWithKey (\_ _ -> Nothing) (toBase i) m of - (Nothing,!m') -> (Nothing,IxMap m') + (Nothing,!m') -> (Nothing,IxMap m') (Just (Some k),!m') -> (Just (unsafeCoerce k),IxMap m') diff --git a/lsp-types/src/Data/Row/Aeson.hs b/lsp-types/src/Data/Row/Aeson.hs new file mode 100644 index 000000000..21be272b5 --- /dev/null +++ b/lsp-types/src/Data/Row/Aeson.hs @@ -0,0 +1,97 @@ +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE UndecidableInstances #-} + +{-| +This module defines orphan `aeson` instances for `Data.Row`. +They differ from the instances in `row-types-aeson` in one crucial respect: they +serialise `Nothing` fields by *omitting* them in the resulting object, and parse absent fields as `Nothing`. +`aeson` can be configured to have this behviour for instances for datatypes, but we want to do this +for record types generically. + +This is crucial to match what LSP clients expect. +-} +module Data.Row.Aeson where + +import Data.Aeson +import Data.Aeson.KeyMap (singleton) +import Data.Aeson.Types (Parser, typeMismatch) +import Data.List (intercalate) + +import Data.Row +import Data.Row.Internal +import qualified Data.Row.Records as Rec + +import Data.Bifunctor (second) +import Data.Functor.Const +import Data.Functor.Identity +import Data.Proxy +import Data.String + +-- `aeson` does not need such a typeclass because it generates code per-instance +-- that handles this, whereas we want to work generically. + +-- | Serialise a value as an entry in a JSON object. This allows customizing the +-- behaviour in the object context, in order to e.g. omit the field. +class ToJSONEntry a where + toJSONEntry :: Key -> a -> Object + +instance {-# OVERLAPPING #-} ToJSON a => ToJSONEntry (Maybe a) where + -- Omit Nothing fields + toJSONEntry _ Nothing = mempty + toJSONEntry k v = singleton k (toJSON v) + +instance {-# OVERLAPPABLE #-} ToJSON a => ToJSONEntry a where + toJSONEntry k v = singleton k (toJSON v) + +class FromJSONEntry a where + parseJSONEntry :: Object -> Key -> Parser a + +instance {-# OVERLAPPING #-} FromJSON a => FromJSONEntry (Maybe a) where + -- Parse Nothing fields as optional + parseJSONEntry o k = o .:? k + +instance {-# OVERLAPPABLE #-} FromJSON a => FromJSONEntry a where + parseJSONEntry o k = o .: k + +------ + +instance Forall r ToJSONEntry => ToJSON (Rec r) where + -- Sadly, there appears to be no helper we can use that gives us access to the keys, so I just used metamorph directly + -- adapted from 'eraseWithLabels' + toJSON rc = Object $ getConst $ metamorph @_ @r @ToJSONEntry @(,) @Rec @(Const Object) @Identity Proxy doNil doUncons doCons rc + where + doNil :: Rec Empty -> Const Object Empty + doNil _ = Const mempty + doUncons + :: forall l r' + . (KnownSymbol l) + => Label l + -> Rec r' + -> (Rec (r' .- l), Identity (r' .! l)) + doUncons l = second Identity . lazyUncons l + doCons + :: forall l t r' + . (KnownSymbol l, ToJSONEntry t) + => Label l + -> (Const Object r', Identity t) + -> Const Object (Extend l t r') + doCons l (Const c, Identity x) = Const $ toJSONEntry (show' l) x <> c + +instance (AllUniqueLabels r, Forall r FromJSONEntry) => FromJSON (Rec r) where + parseJSON (Object o) = do + r <- Rec.fromLabelsA @FromJSONEntry $ \ l -> do + x <- parseJSONEntry o (fromString $ show l) + x `seq` pure x + r `seq` pure r + + parseJSON v = typeMismatch msg v + where msg = "REC: {" ++ intercalate "," (labels @r @FromJSONEntry) ++ "}" + +--- Copied from the library, as it's private + +lazyUncons :: KnownSymbol l => Label l -> Rec r -> (Rec (r .- l), r .! l) +lazyUncons l r = (Rec.lazyRemove l r, r .! l) diff --git a/lsp-types/src/Language/Haskell/TH/Compat.hs b/lsp-types/src/Language/Haskell/TH/Compat.hs new file mode 100644 index 000000000..f04996052 --- /dev/null +++ b/lsp-types/src/Language/Haskell/TH/Compat.hs @@ -0,0 +1,21 @@ +{-# LANGUAGE CPP #-} +module Language.Haskell.TH.Compat + ( addHaddock + ) where + +import Data.Text (Text) +import qualified Language.Haskell.TH as TH +#if MIN_VERSION_template_haskell(2,18,0) +import qualified Data.Text as T +import Data.Functor (void) +#endif + +-- | Compatibility wrapper for the documentation inclusion facility +-- added in `template-haskell-2.18`. +addHaddock :: TH.Name -> Text -> TH.Q () +addHaddock nm doc = +#if MIN_VERSION_template_haskell(2,18,0) + void $ TH.putDoc (TH.DeclDoc nm) (T.unpack doc) +#else + pure () +#endif diff --git a/lsp-types/src/Language/LSP/MetaModel/CodeGen.hs b/lsp-types/src/Language/LSP/MetaModel/CodeGen.hs new file mode 100644 index 000000000..28f8a6dc0 --- /dev/null +++ b/lsp-types/src/Language/LSP/MetaModel/CodeGen.hs @@ -0,0 +1,911 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE PolyKinds #-} +{-# LANGUAGE RecordWildCards #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE StandaloneKindSignatures #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE ViewPatterns #-} +{-| +Code generation of Haskell types and functions based on the LSP metamodel. +-} +module Language.LSP.MetaModel.CodeGen where + +import Language.LSP.MetaModel.Types hiding (MessageDirection (..)) +import qualified Language.LSP.MetaModel.Types as MM +import Language.LSP.Types.Common hiding (MessageKind (..), + Null (..)) +import qualified Language.LSP.Types.Common as C +import qualified Language.LSP.Types.Uri as Uri + +import Control.Lens.Internal.FieldTH +import Control.Lens.TH +import Control.Monad.Reader +import Control.Monad.State (evalStateT) +import qualified Data.Aeson as J +import Data.Foldable (foldl') +import qualified Data.Kind as Kind +import qualified Data.Map as Map +import Data.Maybe (catMaybes, fromMaybe, mapMaybe, + maybeToList) +import Data.Proxy +import Data.Row +import qualified Data.Set as Set +import Data.Text (Text) +import qualified Data.Text as T +import Data.Traversable +import Data.Void +import qualified GHC.TypeLits as TL +import qualified Language.Haskell.TH as TH +import qualified Language.Haskell.TH.Syntax as TH +import Language.Haskell.TH.Compat + +{- +TODO: types are all lazy now, is that right? +-} + +-- | A mapping from names in the metamodel to their names in the generated Haskell. +type SymbolTable = Map.Map Text TH.Name + +-- | A mapping from names in the metamodel to their structure definition, used for chasing +-- supertypes. +type StructTable = Map.Map Text Structure + +data CodeGenEnv = CodeGenEnv { + symbolTable :: SymbolTable + , structTable :: StructTable + } +type CodeGenM = ReaderT CodeGenEnv TH.Q + +-- | Given the metamodel, make a splice with declarations for all the types. +genMetaModel :: MetaModel -> TH.Q [ TH.Dec ] +genMetaModel mm = do + (symbolTable, structTable) <- buildTables mm + flip runReaderT (CodeGenEnv symbolTable structTable) $ do + structs <- concat <$> traverse genStruct (structures mm) + -- Make a binding that just lists all the struct names so we can use them later + -- See Note [Generating lenses] + structNames <- do + -- Have to use the string form of the generated Name + -- since we might have mangled the original name + let structNames = mapMaybe (\Structure{name} -> Map.lookup name symbolTable) (structures mm) + structNameEs <- lift $ traverse (TH.lift . TH.nameBase) structNames + lift + [d| + structNames :: [String] + structNames = $(pure $ TH.ListE structNameEs) + |] + enums <- concat <$> traverse genEnumeration (enumerations mm) + aliases <- traverse genAlias (typeAliases mm) + methods <- genMethods (requests mm) (notifications mm) + pure (structs ++ structNames ++ enums ++ aliases ++ methods) + + -- | Convenience wrapper around 'genMetaModel' that reads the input from a file. +genMetaModelFromFile :: FilePath -> TH.Q [ TH.Dec ] +genMetaModelFromFile fp = do + TH.addDependentFile fp + res <- liftIO $ J.eitherDecodeFileStrict' fp + case res of + Left e -> fail e + Right mm -> genMetaModel mm + +-- | Given a list of type names, make a splice that generates the lens typeclass declarations +-- for all of them. Defined here to avoid stage restrictions. +genLenses :: [String] -> TH.Q [TH.Dec] +genLenses structNames = do + let structNames' = fmap TH.mkName structNames + let + -- We need to use the internals of the lens TH machinery so that we can do this + -- in one go without generating duplicate classes. + opticMaker :: TH.Name -> HasFieldClasses [TH.Dec] + opticMaker n = do + (TH.TyConI d) <- lift $ TH.reify n + makeFieldOpticsForDec' classUnderscoreNoPrefixFields d + decss <- flip evalStateT mempty $ traverse opticMaker structNames' + pure $ concat decss + +------------ + +-- | Names we can't put in Haskell code. +reservedNames :: Set.Set T.Text +reservedNames = Set.fromList [ "data", "type" ] + +-- | Sanitize a name so we can use it in Haskell. +sanitizeName :: T.Text -> T.Text +sanitizeName n = + -- Names can't start with underscores! Replace that with a 'U' for lack + -- of a better idea + let n' = if "_" `T.isPrefixOf` n then T.cons 'U' $ T.tail n else n + -- Names can't have '$'s! Just throw them away. + n'' = T.filter (\c -> c /= '$') n' + -- If we end up with a reserved name, suffix with an underscore. This + -- relibly gets us something recognizable, rather than trying to systematize + -- the conversion of 'type' into 'tpe' or similar. + n''' = if n'' `Set.member` reservedNames then n'' <> "_" else n'' + in n''' + +-- | Make a name to be used at the top-level (i.e. not as a member of anything). +makeToplevelName :: T.Text -> TH.Q TH.Name +makeToplevelName n = TH.newName (T.unpack $ capitalize $ sanitizeName n) + +-- | Make a name for a constructor, optionally including a contextual name to qualify it with. +makeConstrName :: Maybe T.Text -> T.Text -> CodeGenM TH.Name +makeConstrName context n = do + let + cap = capitalize n + disambiguated = case context of { Just t -> t <> "_" <> cap; Nothing -> cap } + pure $ TH.mkName $ T.unpack $ sanitizeName disambiguated + +-- | Make a name for a field. +makeFieldName :: T.Text -> CodeGenM TH.Name +makeFieldName n = do + let + prefixed = "_" <> sanitizeName n + pure $ TH.mkName $ T.unpack prefixed + +-- | Build the tables we need for processing the metamodel. +buildTables :: MetaModel -> TH.Q (SymbolTable, StructTable) +buildTables (MetaModel{structures, enumerations, typeAliases}) = do + bothEntries <- for structures $ \s@Structure{name} -> do + thName <- makeToplevelName name + pure ((name, thName), (name, s)) + let (entries, sentries) = unzip bothEntries + + entries' <- for enumerations $ \Enumeration{name} -> do + thName <- makeToplevelName name + pure (name, thName) + + entries'' <- for typeAliases $ \TypeAlias{name} -> do + thName <- makeToplevelName name + pure (name, thName) + + let symbolTable = Map.fromList $ entries <> entries' <> entries'' + structTable = Map.fromList sentries + + pure (symbolTable, structTable) + +-------- + +-- | Translate a type in the metamodel into the corresponding Haskell type. +-- See Note [Translating metamodel types] +convertType :: Type -> CodeGenM TH.Type +convertType = \case + BaseType n -> case n of + URI -> lift [t| Uri.Uri |] + DocumentUri -> lift [t| Uri.Uri |] + Integer -> lift [t| Int32 |] + UInteger -> lift [t| UInt |] + Decimal -> lift [t| Float |] + RegExp -> lift [t| Text |] + String -> lift [t| Text |] + Boolean -> lift [t| Bool |] + Null -> lift [t| C.Null |] + + -- Special cases: these are in fact defined in the meta model, but + -- we have way better types for them + + -- 'LSPAny' is a big union of anything in the metamodel, we just + -- keep that as an aeson 'Value' + ReferenceType "LSPAny" -> lift [t| J.Value |] + -- 'LSPObject' is an empty structure ... better to just say it's an aeson 'Object'! + ReferenceType "LSPObject" -> lift [t| J.Object |] + -- 'LSPArray' is a list of 'LSPAny'... better to just say it's an aeson 'Array'! + ReferenceType "LSPArray" -> lift [t| J.Array |] + + ReferenceType n -> do + st <- asks symbolTable + case Map.lookup n st of + Just thn -> pure $ TH.ConT thn + Nothing -> fail $ "Reference to unknown type: " <> show n + ArrayType e -> TH.AppT TH.ListT <$> convertType e + MapType k v -> do + kt <- convertType k + vt <- convertType v + pure $ mkIterAppT (TH.ConT ''Map.Map) [ kt, vt ] + OrType es -> do + est <- traverse convertType es + pure $ foldr1 (\ty o -> TH.ConT ''(|?) `TH.AppT` ty `TH.AppT` o) est + AndType es -> do + st <- asks structTable + props <- for es $ \case + ReferenceType t | Just e <- Map.lookup t st -> getStructProperties e + t -> fail $ "element of 'and' type was not a reference to a structure: " ++ show t + genAnonymousStruct $ concat props + StructureLiteralType (StructureLiteral {properties}) -> genAnonymousStruct properties + TupleType es -> do + est <- traverse convertType es + pure $ mkIterAppT (TH.TupleT (length est)) est + StringLiteralType s -> lift [t| AString $(TH.litT $ TH.strTyLit $ T.unpack s) |] + IntegerLiteralType n -> lift [t| AnInteger $(TH.litT $ TH.numTyLit n) |] + -- TODO: support these. They're not used in the metamodel currently + BooleanLiteralType _ -> fail "unsupported: boolean literal types" + +------------ + +-- | Generate a type declaration corresponding to an enumeration. +genEnumeration :: Enumeration -> CodeGenM [TH.Dec] +genEnumeration Enumeration{name, type_, values, supportsCustomValues, documentation, since, proposed} = do + let enumName = name + enumNameString = T.unpack enumName + -- This indicates whether or not the enum is "open" and supports custom values. + -- We need to branch on this a lot! + custom = fromMaybe False supportsCustomValues + + st <- asks symbolTable + tn <- case Map.lookup name st of + Just n -> pure n + Nothing -> fail $ "no name for " ++ show name + addDocumentation tn documentation since proposed + + -- The (Haskell) type of the elements of this enum. Useful, so we can generate various + -- code (e.g. for parsing JSON) generically but use this type to pin down what we want to do. + ty <- case type_ of + BaseType Integer -> lift [t| Int32 |] + BaseType UInteger -> lift [t| UInt |] + BaseType String -> lift [t| Text |] + _ -> fail $ "enumeration of unexpected type " ++ show type_ + + -- https://github.com/microsoft/vscode-languageserver-node/issues/1035 + let badEnumValues = ["jsonrpcReservedErrorRangeStart", "jsonrpcReservedErrorRangeEnd", "serverErrorStart", "serverErrorEnd"] + values' = filter (\EnumerationEntry{name} -> not $ name `elem` badEnumValues) values + -- The associations between constructor names and their literals + assocs <- for values' $ \EnumerationEntry{name, value, documentation, since, proposed} -> do + cn <- makeConstrName (Just enumName) name + addDocumentation cn documentation since proposed + let + -- The literal for the actual enum value in this case + lit = case value of + T t -> TH.StringL $ T.unpack t + I i -> TH.IntegerL i + pure (cn, lit) + + let normalCons = fmap (\(cn, _) -> TH.NormalC cn []) assocs + customCon <- + if custom + then do + cn <- makeConstrName (Just enumName) "Custom" + lift $ addHaddock cn "Custom values not defined in the LSP specification." + pure $ Just $ TH.NormalC cn [(noBang, ty)] + else pure Nothing + let cons = normalCons ++ maybeToList customCon + + let datad = TH.DataD [] tn [] Nothing cons [stockDeriving] + + -- Generate functions for converting between the enum and its base representation. These + -- are handy for defining e.g. JSON conversions simply. + -- TODO: could do this with a class? Unclear if that's nicer or not + -- xToValue :: X -> Value + toBaseTypeN <- lift $ TH.newName $ T.unpack $ uncapitalize (sanitizeName enumName) <> "ToValue" + toBaseTypeD <- do + -- xToValue X1 = + let normalClauses = (flip fmap) assocs $ \(n, v) -> TH.Clause [TH.ConP n []] (TH.NormalB $ TH.LitE v) [] + -- xToValue (CustomX c) = c + customClause <- case customCon of + Just (TH.NormalC cn _) -> do + vn <- lift $ TH.newName "n" + pure $ Just $ TH.Clause [TH.ConP cn [TH.VarP vn]] (TH.NormalB (TH.VarE vn)) [] + Just _ -> fail "impossible: wrong custom constructor" + Nothing -> pure Nothing + let clauses = normalClauses ++ maybeToList customClause + sd = TH.SigD toBaseTypeN (TH.ArrowT `TH.AppT` TH.ConT tn `TH.AppT` ty) + fd = TH.FunD toBaseTypeN clauses + pure [ sd, fd ] + + -- Result type is Maybe unless X allows custom values, in which case we can always interpret + -- a base value as a custom member + -- valueToX :: -> Maybe X + -- valueToX :: -> X + fromBaseTypeN <- lift $ TH.newName $ T.unpack $ "valueTo" <> capitalize (sanitizeName enumName) + fromBaseTypeD <- do + -- valueToX = X + -- or + -- valueToX = Just X + let normalClauses = (flip fmap) assocs $ \(n, v) -> TH.Clause [TH.LitP v] (TH.NormalB $ if custom then TH.ConE n else TH.VarE 'pure `TH.AppE` TH.ConE n) [] + -- valueToX c = CustomX c + -- or + -- valueToX _ = Nothing + fallThroughClause <- case customCon of + Just (TH.NormalC cn _) -> do + n <- lift $ TH.newName "n" + pure $ TH.Clause [TH.VarP n] (TH.NormalB (TH.ConE cn `TH.AppE` TH.VarE n)) [] + Just _ -> fail "impossible: wrong custom constructor" + Nothing -> pure $ TH.Clause [TH.WildP] (TH.NormalB (TH.ConE 'Nothing)) [] + let clauses = normalClauses ++ [fallThroughClause] + sd = TH.SigD fromBaseTypeN (TH.ArrowT `TH.AppT` ty `TH.AppT` (if custom then TH.ConT tn else TH.ConT ''Maybe `TH.AppT` TH.ConT tn)) + fd = TH.FunD fromBaseTypeN clauses + pure [sd, fd] + + -- JSON instances in terms of the conversion functions. These are straighftorward, but still good to generate since there are so many! + jsonDs <- lift + [d| + instance J.ToJSON $(TH.conT tn) where + toJSON e = J.toJSON ($(TH.varE toBaseTypeN) e) + + instance J.FromJSON $(TH.conT tn) where + parseJSON val = do + v <- J.parseJSON val + $( + if custom + then [| pure $ $(TH.varE fromBaseTypeN) v |] + else [| case $(TH.varE fromBaseTypeN) v of { Just e -> pure e; Nothing -> fail $ "unrecognized enum value for " ++ enumNameString ++ ":" ++ show v; } |] + ) + |] + + pure $ [datad] ++ toBaseTypeD ++ fromBaseTypeD ++ jsonDs + +-- | Generate a type declaration corresponding to a type alias. +genAlias :: TypeAlias -> CodeGenM TH.Dec +genAlias TypeAlias{name, type_, documentation, since, proposed} = do + st <- asks symbolTable + tn <- case Map.lookup name st of + Just n -> pure n + Nothing -> fail $ "no name for " ++ show name + addDocumentation tn documentation since proposed + + rhs <- convertType type_ + + ctor <- makeConstrName Nothing name + -- We don't actually need JSONKey instances for all the base types, but it's close enough + let jsonKey = case type_ of { BaseType _ -> True; _ -> False } + newtypeDeriving = TH.DerivClause (Just TH.NewtypeStrategy) + ([TH.ConT ''J.ToJSON, TH.ConT ''J.FromJSON] ++ if jsonKey then [TH.ConT ''J.ToJSONKey, TH.ConT ''J.FromJSONKey] else []) + pure $ TH.NewtypeD [] tn [] Nothing (TH.NormalC ctor [(noBang, rhs)]) [stockDeriving, newtypeDeriving] + --pure $ TH.TySynD tn [] rhs + +(.=?) :: (J.KeyValue kv, J.ToJSON v) => J.Key -> Maybe v -> [kv] +k .=? v = case v of + Just v' -> [k J..= v'] + Nothing -> mempty + +-- | Generate a type declaration corresponding to a top-level named struct. +genStruct :: Structure -> CodeGenM [TH.Dec] +genStruct s@Structure{name, documentation, since, proposed} = do + let structName = name + + st <- asks symbolTable + tn <- case Map.lookup name st of + Just n -> pure n + Nothing -> fail $ "no name for " ++ show name + addDocumentation tn documentation since proposed + + ctor <- lift $ makeToplevelName name + + props <- getStructProperties s + args <- for props $ \Property{name, type_, optional, documentation, since, proposed} -> do + pty <- convertType type_ + let mty = case optional of + Just True -> TH.ConT ''Maybe `TH.AppT` pty + _ -> pty + n <- makeFieldName name + addDocumentation n documentation since proposed + pure (name, (n, noBang, mty)) + + let datad = TH.DataD [] tn [] Nothing [TH.RecC ctor (fmap snd args)] [stockDeriving] + + toJsonD <- do + (unzip -> (args, pairEs)) <- for props $ \Property{name, optional} -> do + n <- lift $ TH.newName "arg" + pairE <- case optional of + Just True -> lift [| $(TH.litE $ TH.stringL $ T.unpack name) .=? $(TH.varE n) |] + _ -> lift [| [$(TH.litE $ TH.stringL $ T.unpack name) J..= $(TH.varE n)] |] + pure (n, pairE) + body <- lift [| J.object $ concat $ $(TH.listE (fmap pure pairEs)) |] + let toJsonF = TH.FunD 'J.toJSON [TH.Clause [TH.ConP ctor (fmap TH.VarP args)] (TH.NormalB body) []] + pure $ TH.InstanceD Nothing [] (TH.ConT ''J.ToJSON `TH.AppT` TH.ConT tn) [toJsonF] + + fromJsonD <- do + vn <- lift $ TH.newName "v" + exprs <- for props $ \Property{name, optional} -> + case optional of + Just True -> lift [| $(TH.varE vn) J..:! $(TH.litE $ TH.stringL $ T.unpack name)|] + _ -> lift [| $(TH.varE vn) J..: $(TH.litE $ TH.stringL $ T.unpack name)|] + let lamBody = mkIterApplicativeApp (TH.ConE ctor) exprs + body <- lift [| J.withObject $(TH.litE $ TH.stringL $ T.unpack structName) $ \ $(TH.varP vn) -> $lamBody |] + let fromJsonF = TH.FunD 'J.parseJSON [TH.Clause [] (TH.NormalB body) []] + pure $ TH.InstanceD Nothing [] (TH.ConT ''J.FromJSON `TH.AppT` TH.ConT tn) [fromJsonF] + + pure [datad, toJsonD, fromJsonD] + +-- | Get the list of properties of a struct, including inherited ones. +getStructProperties :: Structure -> CodeGenM [Property] +getStructProperties s@Structure{name, properties, extends, mixins} = do + st <- asks structTable + let + extends' = fromMaybe [] extends + mixins' = fromMaybe [] mixins + supertypes = extends' ++ mixins' + superProps <- for supertypes $ \case + ReferenceType t | Just e <- Map.lookup t st -> getStructProperties e + t -> fail $ "supertype of structure " ++ show name ++ " was not a reference to a structure: " ++ show t + let allSuperProps = concat superProps + -- If a property is redefined in the current type, then it overrides the inherited one + localNames = foldMap (\Property{name} -> Set.singleton name) properties + filteredSuperProps = filter (\Property{name} -> name `Set.notMember` localNames) allSuperProps + pure (filteredSuperProps ++ properties) + +-- | Generate a type corresponding to an anonymous struct. +genAnonymousStruct :: [Property] -> CodeGenM TH.Type +genAnonymousStruct properties = do + row <- for properties $ \Property{name, type_, optional} -> do + pty <- convertType type_ + let mty = case optional of + Just True -> TH.ConT ''Maybe `TH.AppT` pty + _ -> pty + pure $ TH.ConT ''(.==) `TH.AppT` TH.LitT (TH.StrTyLit (T.unpack name)) `TH.AppT` mty + let tyList = foldr (\ty l -> TH.ConT ''(.+) `TH.AppT` ty `TH.AppT` l) (TH.ConT ''Empty) row + pure $ TH.AppT (TH.ConT ''Rec) tyList + +-------------- + +data RequestData = RequestData + { methCon :: TH.Con + , singCon :: TH.Con + , paramsEq :: TH.TySynEqn + , resultEq :: TH.TySynEqn + , errorDataEq :: TH.TySynEqn + , registrationOptionsEq :: TH.TySynEqn + , toStringClause :: TH.Clause + , fromStringClause :: TH.Clause + , messageDirectionClause :: TH.Clause + , messageKindClause :: TH.Clause + } + +data NotificationData = NotificationData + { methCon :: TH.Con + , singCon :: TH.Con + , paramsEq :: TH.TySynEqn + , registrationOptionsEq :: TH.TySynEqn + , toStringClause :: TH.Clause + , fromStringClause :: TH.Clause + , messageDirectionClause :: TH.Clause + , messageKindClause :: TH.Clause + } + +data CustomData = CustomData + { methCon :: TH.Con + , singCon :: TH.Con + , paramsEq :: TH.TySynEqn + , resultEq :: TH.TySynEqn + , errorDataEq :: TH.TySynEqn + , registrationOptionsEq :: TH.TySynEqn + , toStringClause :: TH.Clause + , fromStringClause :: TH.Clause + , messageDirectionClause :: TH.Clause + , messageKindClause :: TH.Clause + } + +-- TODO: partial result params +genMethods :: [Request] -> [Notification] -> CodeGenM [TH.Dec] +genMethods reqs nots = do + mtyN <- lift $ TH.newName "Method" + -- These are the type variables for the main type declaration, we will need them for + -- some of the constructor declarations + fN <- lift $ TH.newName "f" + tN <- lift $ TH.newName "t" + lift $ addHaddock mtyN "A type representing a LSP method (or class of methods), intended to be used mostly at the type level." + + styN <- lift $ TH.newName "SMethod" + lift $ addHaddock styN "A singleton type for 'Method'." + + sstyN <- lift $ TH.newName "SomeMethod" + lift $ addHaddock sstyN "A method which isn't statically known." + -- We will want to refer to the constructor in some places + smcn <- lift $ TH.newName "SomeMethod" + + mpN <- lift $ TH.newName "MessageParams" + lift $ addHaddock mpN "Maps a LSP method to its parameter type." + + mrN <- lift $ TH.newName "MessageResult" + lift $ addHaddock mrN "Maps a LSP method to its result type." + + edN <- lift $ TH.newName "ErrorData" + lift $ addHaddock edN "Maps a LSP method to its error data type." + + roN <- lift $ TH.newName "RegistrationOptions" + lift $ addHaddock roN "Maps a LSP method to its registration options type." + + toStringN <- lift $ TH.newName "someMethodToMethodString" + lift $ addHaddock toStringN "Turn a 'SomeMethod' into its LSP method string." + fromStringN <- lift $ TH.newName "methodStringToSomeMethod" + lift $ addHaddock fromStringN "Turn a LSP method string into a 'SomeMethod'." + + mdN <- lift $ TH.newName "messageDirection" + lift $ addHaddock mdN "Get a singleton witness for the message direction of a method." + mtN <- lift $ TH.newName "messageKind" + lift $ addHaddock mtN "Get a singleton witness for the message kind of a method." + + let methodName context fullName = + let pieces = T.splitOn "/" fullName + -- TODO: don't like this + in makeConstrName (Just context) $ foldMap capitalize pieces + let messagePartType t = case t of + Just ty -> convertType ty + -- See Note [Absent parameters/results/errors] + Nothing -> lift [t| Maybe Void |] + + -- Construct the various pieces we'll need for the declarations in one go + reqData <- for reqs $ \Request{method, params, result, errorData, registrationOptions, messageDirection} -> do + -- :: Method + mcn <- methodName "Method" method + let direction = case messageDirection of + MM.ClientToServer -> TH.PromotedT 'ClientToServer + MM.ServerToClient -> TH.PromotedT 'ServerToClient + MM.Both -> TH.VarT fN + let methCon = TH.GadtC [mcn] [] (mkIterAppT (TH.ConT mtyN) [direction, TH.PromotedT 'C.Request]) + + scn <- methodName "SMethod" method + let singCon = TH.GadtC [scn] [] (mkIterAppT (TH.ConT styN) [TH.PromotedT mcn]) + + -- MessageParams = + paramTy <- messagePartType params + let paramsEq = TH.TySynEqn Nothing (TH.ConT mpN `TH.AppT` TH.ConT mcn) paramTy + -- MessageResult = + resultTy <- messagePartType (Just result) + let resultEq = TH.TySynEqn Nothing (TH.ConT mrN `TH.AppT` TH.ConT mcn) resultTy + errDatTy <- messagePartType errorData + let errorDataEq = TH.TySynEqn Nothing (TH.ConT edN `TH.AppT` TH.ConT mcn) errDatTy + regOptsTy <- messagePartType registrationOptions + let registrationOptionsEq = TH.TySynEqn Nothing (TH.ConT roN `TH.AppT` TH.ConT mcn) regOptsTy + + r <- lift $ TH.newName "r" + let + mnLit = TH.StringL $ T.unpack method + toStringClause = TH.Clause [TH.ConP smcn [TH.ConP scn []]] (TH.NormalB $ TH.LitE mnLit) [] + fromStringClause = TH.Clause [TH.LitP mnLit] (TH.NormalB $ TH.ConE smcn `TH.AppE` TH.ConE scn) [] + messageDirectionClause = + let d = case messageDirection of + MM.ClientToServer -> TH.ConE 'SClientToServer + MM.ServerToClient -> TH.ConE 'SServerToClient + MM.Both -> TH.ConE 'SBothDirections + in TH.Clause [TH.ConP scn []] (TH.NormalB d) [] + messageKindClause = TH.Clause [TH.ConP scn []] (TH.NormalB $ TH.ConE 'SRequest) [] + + pure $ RequestData {..} + + notData <- for nots $ \Notification{method, params, registrationOptions, messageDirection} -> do + mcn <- methodName "Method" method + let direction = case messageDirection of + MM.ClientToServer -> TH.PromotedT 'ClientToServer + MM.ServerToClient -> TH.PromotedT 'ServerToClient + MM.Both -> TH.VarT fN + let methCon = TH.GadtC [mcn] [] (mkIterAppT (TH.ConT mtyN) [direction, TH.PromotedT 'C.Notification]) + + scn <- methodName "SMethod" method + let singCon = TH.GadtC [scn] [] (mkIterAppT (TH.ConT styN) [TH.PromotedT mcn]) + + -- MessageParams = + paramTy <- messagePartType params + let paramsEq = TH.TySynEqn Nothing (TH.ConT mpN `TH.AppT` TH.ConT mcn) paramTy + regOptsTy <- messagePartType registrationOptions + let registrationOptionsEq = TH.TySynEqn Nothing (TH.ConT roN `TH.AppT` TH.ConT mcn) regOptsTy + + r <- lift $ TH.newName "r" + let + mnLit = TH.StringL $ T.unpack method + toStringClause = TH.Clause [TH.ConP smcn [TH.ConP scn []]] (TH.NormalB $ TH.LitE mnLit) [] + fromStringClause = TH.Clause [TH.LitP mnLit] (TH.NormalB $ TH.ConE smcn `TH.AppE` TH.ConE scn) [] + messageDirectionClause = + let d = case messageDirection of + MM.ClientToServer -> TH.ConE 'SClientToServer + MM.ServerToClient -> TH.ConE 'SServerToClient + MM.Both -> TH.ConE 'SBothDirections + in TH.Clause [TH.ConP scn []] (TH.NormalB d) [] + messageKindClause = TH.Clause [TH.ConP scn []] (TH.NormalB $ TH.ConE 'SNotification) [] + + pure $ NotificationData {..} + + -- Add the custom method case, which isn't in the metamodel + customDat <- do + mcn <- methodName "Method" "CustomMethod" + -- Method_CustomMethod :: Symbol -> Method f t + let methCon = TH.GadtC [mcn] [(noBang, TH.ConT ''TL.Symbol)] (mkIterAppT (TH.ConT mtyN) [TH.VarT fN, TH.VarT tN]) + -- SMethod_CustomMethod :: KnownSymbol s => SMethod Method_CustomMethod + scn <- methodName "SMethod" "CustomMethod" + syn <- lift $ TH.newName "s" + let singCon = + TH.ForallC [TH.PlainTV syn TH.SpecifiedSpec] [TH.ConT ''TL.KnownSymbol `TH.AppT` TH.VarT syn] $ + TH.GadtC [scn] [(noBang, TH.ConT ''Proxy `TH.AppT` TH.VarT syn)] (TH.ConT styN `TH.AppT` (TH.PromotedT mcn `TH.AppT` TH.VarT syn)) + -- MessageParams Method_CustomMethod = Value + let paramsEq = TH.TySynEqn Nothing (TH.ConT mpN `TH.AppT` (TH.ConT mcn `TH.AppT` TH.VarT syn)) (TH.ConT ''J.Value) + -- MessageResult Method_CustomMethod = Value + let resultEq = TH.TySynEqn Nothing (TH.ConT mrN `TH.AppT` (TH.ConT mcn `TH.AppT` TH.VarT syn)) (TH.ConT ''J.Value) + -- Can shove whatever you want in the error data for custom methods? + -- ErrorData Method_CustomMethod = Value + let errorDataEq = TH.TySynEqn Nothing (TH.ConT edN `TH.AppT` (TH.ConT mcn `TH.AppT` TH.VarT syn)) (TH.ConT ''J.Value) + -- Can't register custom methods + -- RegistrationOptions Method_CustomMethod = Void + let registrationOptionsEq = TH.TySynEqn Nothing (TH.ConT roN `TH.AppT` (TH.ConT mcn `TH.AppT` TH.VarT syn)) (TH.ConT ''Void) + + v <- lift $ TH.newName "v" + fromStringBody <- lift [| + case TL.someSymbolVal $(TH.varE v) of + TL.SomeSymbol p -> SomeMethod (SMethod_CustomMethod p) + |] + let + toStringClause = TH.Clause [TH.ConP smcn [TH.ConP scn [TH.VarP v]]] (TH.NormalB $ TH.VarE 'TL.symbolVal `TH.AppE` TH.VarE v) [] + fromStringClause = TH.Clause [TH.VarP v] (TH.NormalB fromStringBody) [] + messageDirectionClause = TH.Clause [TH.ConP scn [TH.WildP]] (TH.NormalB $ TH.ConE 'SBothDirections) [] + messageKindClause = TH.Clause [TH.ConP scn [TH.WildP]] (TH.NormalB $ TH.ConE 'SBothTypes) [] + + pure $ CustomData {..} + + let mkMethodTv = do + fN <- lift $ TH.newName "f" + tN <- lift $ TH.newName "t" + mN <- lift $ TH.newName "m" + pure $ TH.KindedTV mN () (TH.ConT mtyN `TH.AppT` TH.VarT fN `TH.AppT` TH.VarT tN) + + dataD <- do + let tyArgs = [TH.KindedTV fN () (TH.ConT ''MessageDirection), TH.KindedTV tN () (TH.ConT ''C.MessageKind)] + ctors = fmap (\RequestData{..} -> methCon) reqData ++ fmap (\NotificationData{..} -> methCon) notData ++ [(\CustomData{..} -> methCon) customDat] + -- This only really exists on the type level so we don't really want instances anyway + pure $ TH.DataD [] mtyN tyArgs Nothing ctors [] + singD <- do + mtv <- mkMethodTv + let ctors = fmap (\RequestData{..} -> singCon) reqData ++ fmap (\NotificationData{..} -> singCon) notData ++ [(\CustomData{..} -> singCon) customDat] + sig <- lift $ TH.kiSigD styN [t| forall f t . $(TH.conT mtyN) f t -> Kind.Type |] + -- Can't derive instances, it's a GADT, will do them later + let decl = TH.DataD [] styN [mtv] Nothing ctors [] + pure [sig, decl] + ssmD <- do + mn <- lift $ TH.newName "m" + let ctor = TH.ForallC [TH.PlainTV mn TH.SpecifiedSpec] [] $ TH.GadtC [smcn] [(noBang, TH.ConT styN `TH.AppT` TH.VarT mn)] (TH.ConT sstyN) + -- Can't derive instances because we're not doing the instances for SMethod here either + pure $ TH.DataD [] sstyN [] Nothing [ctor] [] + mpD <- do + mtv <- mkMethodTv + sig <- lift $ TH.kiSigD mpN [t| forall f t . $(TH.conT mtyN) f t -> Kind.Type |] + let eqns = fmap (\RequestData{..} -> paramsEq) reqData ++ fmap (\NotificationData{..} -> paramsEq) notData ++ [(\CustomData{..} -> paramsEq) customDat] + hd = TH.TypeFamilyHead mpN [mtv] (TH.KindSig (TH.ConT ''Kind.Type)) Nothing + decl = TH.ClosedTypeFamilyD hd eqns + pure [sig, decl] + mrD <- do + mtv <- mkMethodTv + sig <- lift $ TH.kiSigD mrN [t| forall f t . $(TH.conT mtyN) f t -> Kind.Type |] + let eqns = fmap (\RequestData{..} -> resultEq) reqData ++ [(\CustomData{..} -> resultEq) customDat] + hd = TH.TypeFamilyHead mrN [mtv] (TH.KindSig (TH.ConT ''Kind.Type)) Nothing + decl = TH.ClosedTypeFamilyD hd eqns + pure [sig, decl] + edD <- do + mtv <- mkMethodTv + sig <- lift $ TH.kiSigD edN [t| forall f t . $(TH.conT mtyN) f t -> Kind.Type |] + let eqns = fmap (\RequestData{..} -> errorDataEq) reqData ++ [(\CustomData{..} -> errorDataEq) customDat] + hd = TH.TypeFamilyHead edN [mtv] (TH.KindSig (TH.ConT ''Kind.Type)) Nothing + decl = TH.ClosedTypeFamilyD hd eqns + pure [sig, decl] + roD <- do + mtv <- mkMethodTv + sig <- lift $ TH.kiSigD roN [t| forall f t . $(TH.conT mtyN) f t -> Kind.Type |] + let eqns = fmap (\RequestData{..} -> registrationOptionsEq) reqData ++ fmap (\NotificationData{..} -> registrationOptionsEq) notData ++ [(\CustomData{..} -> registrationOptionsEq) customDat] + hd = TH.TypeFamilyHead roN [mtv] (TH.KindSig (TH.ConT ''Kind.Type)) Nothing + decl = TH.ClosedTypeFamilyD hd eqns + pure [sig, decl] + + -- methodToString :: SomeMethod -> Text + toStringD <- do + let clauses = fmap (\RequestData{..} -> toStringClause) reqData ++ fmap (\NotificationData{..} -> toStringClause) notData ++ [(\CustomData{..} -> toStringClause) customDat] + sd = TH.SigD toStringN (TH.ArrowT `TH.AppT` TH.ConT sstyN `TH.AppT` TH.ConT ''String) + fd = TH.FunD toStringN clauses + pure [ sd, fd ] + -- stringToMethod :: Text -> SomeMethod + fromStringD <- do + let clauses = fmap (\RequestData{..} -> fromStringClause) reqData ++ fmap (\NotificationData{..} -> fromStringClause) notData ++ [(\CustomData{..} -> fromStringClause) customDat] + sd = TH.SigD fromStringN (TH.ArrowT `TH.AppT` TH.ConT ''String `TH.AppT` TH.ConT sstyN) + fd = TH.FunD fromStringN clauses + pure [ sd, fd ] + + messageSingD <- do + let fn = TH.mkName "f" + let tn = TH.mkName "t" + let mn = TH.mkName "m" + let mty = TH.ConT mtyN `TH.AppT` TH.VarT fn `TH.AppT` TH.VarT tn + tyVars = [TH.PlainTV fn TH.SpecifiedSpec, TH.PlainTV tn TH.SpecifiedSpec, TH.KindedTV mn TH.SpecifiedSpec mty] + inTy = TH.ConT styN `TH.AppT` TH.VarT mn + + -- messageDirection + let clauses = fmap (\RequestData{..} -> messageDirectionClause) reqData ++ fmap (\NotificationData{..} -> messageDirectionClause) notData ++ [(\CustomData{..} -> messageDirectionClause) customDat] + outTy = TH.ConT ''SMessageDirection `TH.AppT` TH.VarT fn + funTy = TH.ArrowT `TH.AppT` inTy `TH.AppT` outTy + sd1 = TH.SigD mdN (TH.ForallT tyVars [] funTy) + fd1 = TH.FunD mdN clauses + -- messageKind + let clauses = fmap (\RequestData{..} -> messageKindClause) reqData ++ fmap (\NotificationData{..} -> messageKindClause) notData ++ [(\CustomData{..} -> messageKindClause) customDat] + outTy = TH.ConT ''SMessageKind `TH.AppT` TH.VarT tn + funTy = TH.ArrowT `TH.AppT` inTy `TH.AppT` outTy + sd2 = TH.SigD mtN (TH.ForallT tyVars [] funTy) + fd2 = TH.FunD mtN clauses + pure [ sd1, fd1, sd2, fd2 ] + + pure $ [dataD] ++ singD ++ [ssmD] ++ mpD ++ mrD ++ edD ++ roD ++ toStringD ++ fromStringD ++ messageSingD + +-------------- + +addDocumentation :: TH.Name -> Maybe Text -> Maybe Text -> Maybe Bool -> CodeGenM () +addDocumentation nm doc since proposed = + let docLines = catMaybes [doc, since, fmap (T.pack . show) proposed ] + in + if null docLines + then pure () + else lift $ addHaddock nm $ T.unlines docLines + +----------------- + +capitalize :: T.Text -> T.Text +capitalize s = T.toUpper (T.singleton (T.head s)) `T.append` T.tail s + +uncapitalize :: T.Text -> T.Text +uncapitalize s = T.toLower (T.singleton (T.head s)) `T.append` T.tail s + +mkIterAppT :: TH.Type -> [TH.Type] -> TH.Type +mkIterAppT = foldl' TH.AppT + +mkNestedTupleT :: [TH.Type] -> TH.Type +mkNestedTupleT es = + let l = length es + in if l < 62 + then mkIterAppT (TH.TupleT l) es + else let (es1, es2) = splitAt (l `div` 2) es + in mkIterAppT (TH.TupleT 2) [mkNestedTupleT es1, mkNestedTupleT es2] + +-- | Generate code of the form 'hd <$> a1 <*> ... <*> an' +mkIterApplicativeApp :: TH.Exp -> [TH.Exp] -> TH.Q TH.Exp +mkIterApplicativeApp hd = go + where + go [] = [| pure $(pure hd) |] + go (a:rest) = do + acc <- [| $(pure hd) <$> $(pure a)|] + go' acc rest + go' acc [] = pure acc + go' acc (a:rest) = do + acc' <- [| $(pure acc) <*> $(pure a)|] + go' acc' rest + +noBang :: TH.Bang +noBang = TH.Bang TH.NoSourceUnpackedness TH.NoSourceStrictness + +stockDeriving :: TH.DerivClause +stockDeriving = TH.DerivClause (Just TH.StockStrategy) + [ TH.ConT ''Show + , TH.ConT ''Eq + , TH.ConT ''Ord + -- This makes things very slow + --, TH.ConT ''Generic + ] + +{- Note [Anonymous records] +We need anonymous records in a few places. We could lift each of these to the top +level and declare a new Haskell record type for them, but this requires us to make +lots of arbitrary choices (e.g. what do we call all these new types?) and takes us +further from representing the metamodel accurately. So we instead use an actual +anonymous records library, in this case `row-types`. +-} + +{- Note [Avoiding name clashes] +It is difficult to avoid name clashes, especially since we don't control the input +source. And there are plenty of name clashes in the metamodel. + +One approach would be to generate lots of modules and use Haskell's module system +to disambiguate. But this is not easy with TH: we'd have to write each module ourselves +and split up the logic, whereas it actually makes much more sense to do the generation +all together. + +So that suggests we just need to pick non-clashing names. The crude heuristic +we have adopted is to prefix many values with the name of the type with which they +are associated, followed by an underscore. So the constructors of `X` will be +`X_A`, `X_B` etc. + +We don't do this for fields, instead we rely on `DuplicateRecordFields` and +use classy lenses. +-} + +{- See Note [Translating metamodel types] + += Or types + +Or types are translated directly into anonymous unions using '(|?)'. + += And types + +And types are difficult to handle in general (it's not even clear what that means). We assume +that they contain only references to structures, and translate them as anonymous records +with the union of the fields of the components of the and type. + += Null + +We would like a type that reliably serializes to/from null, since null alternatives +are called out explicitly in the LSP spec. In the end, we just defined our own: 'Null'. + += Enumerations + +Enumerations are compiled as simple sum types. + +Enums that allow custom values get a special extra constructor for that. + += Type aliases + +Type aliases are compiled to newtype definitions. + +The alternative would be to compile them to type aliases. It's not at all clear which +one is better, but this way is closer to how we did things before and in some cases +makes things easier (e.g. when there is a type alias for an anoymous record you get +slightly better errors before you go under the newtype). + += Structures + +Top level strutures are compiled into record datatypes. + +Properties for structures are included in the following order: +- Properties from types in 'extends' (including all their inherited properties). +- Properties from types in 'mixins' (including all their inherited properties). +- Properties defined in the struct itself. + +We insist that extended and mixed in types are references to top-level structures (it's +unclear that anything else makes sense). + +Field names for structure properties are not disambiguated: we rely on `DuplicateRecordFields`. +We generate lenses for conveniently accessing all the duplicate fields, hence +the fields themselves are prefixed with an underscore so they don't clash with the lenses. + +== Optional fields + +Optional fields are translated as 'Maybe' types. We can configure `aeson` to do the right thing +for datatypes, and for anonymous records we have our own instances in 'Data.Row.Aeson'. + +== Structure literals + +Structure literals are translated directly as anonymous records. + +== String/integer literals + +String and integer literal types are weird. They're inhabited by only that specific +string or integer. They're often used for "kind" fields i.e. to encode sum types. +We do try to represent this faithfully, so we have types 'AString' and 'AnInteger' +which behave like this. + +-} + +{- Note [Generating code for methods] +The code generation for methods is in many ways the most complicated part, +because there are some type-level parts. We follow the same basic approach as the +old way: +- A 'Method' type that represents a method, with type parameters for direction and +type (notification/request). +- A 'SMethod' singleton GADT indexed by a 'Method' that can be passed around at runtime. +- A variety of type families for mapping 'Method's to their parameter types, result types, etc. + +We also generate a few functions. The ultimate goal would be to avoid any non-generated +code having to do a full pattern match on 'Method', since it's gigantic and that's not +very maintainable. We don't quite achieve that yet. +-} + +{- Note [Absent parameters/results/errors] +Many methods don't *have* parameters/results/errors. What are we supposed to do there? +We can't say the type is 'Null', because the client will send us messages where the +value is absent, not just null. We really need a way to say the value is *absent*. + +We have a cunning trick for this: use 'Maybe Void'. That can only ever be 'Nothing', +and sine we're configuring aeson to omit 'Nothing' fields in objects, that's exactly +what we want. + +See also https://github.com/haskell/aeson/issues/646 for some relevant discussion. +-} + +{- Note [Generating lenses] +We would like to use the TH from 'lens' to generate lenses. However, this is tricky because +a) It uses 'reify' +b) It creates typeclass instances + +Fact a) means it can't be run in the same splice as the one in which we generate the +types. The normal workaround is to run it with 'addModFinalizer'... but code which +runs there can't generate typecalss instances! + +So we're a bit stuck. The solution I came up with is to generate a binding that lists +all the names of the types we want to generate lenses for (as 'String's, not 'Name's, +see https://gitlab.haskell.org/ghc/ghc/-/issues/21759), and then run the lens-generation +TH in another module. Which is clunky, but works. +-} diff --git a/lsp-types/src/Language/LSP/MetaModel/Types.hs b/lsp-types/src/Language/LSP/MetaModel/Types.hs new file mode 100644 index 000000000..4ed30be0c --- /dev/null +++ b/lsp-types/src/Language/LSP/MetaModel/Types.hs @@ -0,0 +1,225 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-| +This defines the types of the LSP "metamodel", which is a machine-readable format specifying the +types used in the LSP protocol. + +The type system is quite typescript-y, which isn't surprising given that the whole protocol is +very typescript-y. + +A typescript version of the metamodel types can be found here, which is useful for constructing +this Haskell model of them: +https://github.com/microsoft/vscode-languageserver-node/blob/main/tools/src/metaModel.ts +-} +module Language.LSP.MetaModel.Types where + +import Data.Aeson hiding (Null, String) +import qualified Data.Aeson as JSON +import qualified Data.Aeson.TH as JSON +import qualified Data.Char as Char +import Data.Text (Text) + +import Control.Lens +import qualified Data.List.NonEmpty as NE + +data MessageDirection = ServerToClient | ClientToServer | Both + deriving (Show, Eq, Ord) + +instance ToJSON MessageDirection where + toJSON ServerToClient = toJSON @String "serverToClient" + toJSON ClientToServer = toJSON @String "clientToServer" + toJSON Both = toJSON @String "both" + +instance FromJSON MessageDirection where + parseJSON = withText "MessageDirection" $ \case + "serverToClient" -> pure ServerToClient + "clientToServer" -> pure ClientToServer + "both" -> pure Both + t -> fail $ "unknown message direction " ++ show t + +data BaseTypeName = URI | DocumentUri | Integer | UInteger | Decimal | RegExp | String | Boolean | Null + deriving (Show, Eq, Ord) + +data Property = Property + { name :: Text + , type_ :: Type + , optional :: Maybe Bool + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data StructureLiteral = StructureLiteral + { properties :: [Property] + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data Type = + BaseType { btName :: BaseTypeName } + | ReferenceType { rtName :: Text } + | ArrayType { atElement :: Type } + | MapType { mKey :: Type, mValue :: Type } + | AndType { aItems :: NE.NonEmpty Type } + | OrType { oItems :: NE.NonEmpty Type } + | TupleType { tItems :: [Type] } + | StructureLiteralType { stlValue :: StructureLiteral } + | StringLiteralType { slValue :: Text } + | IntegerLiteralType { ilValue :: Integer } + | BooleanLiteralType { blValue :: Bool } + deriving (Show, Eq, Ord) + +data Request = Request + { method :: Text + , params :: Maybe Type -- typescript says it can be [Type], but it never is so whatever + , result :: Type + , partialResult :: Maybe Type + , errorData :: Maybe Type + , registrationOptions :: Maybe Type + , messageDirection :: MessageDirection + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data Notification = Notification + { method :: Text + , params :: Maybe Type + , registrationOptions :: Maybe Type + , messageDirection :: MessageDirection + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data Structure = Structure + { name :: Text + , extends :: Maybe [Type] + , mixins :: Maybe [Type] + , properties :: [Property] + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data TypeAlias = TypeAlias + { name :: Text + , type_ :: Type + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +-- This is just 'string | int' on the typescript side. +data TextOrInteger = T Text | I Integer + deriving (Show, Eq, Ord) + +data EnumerationEntry = EnumerationEntry + { name :: Text + , value :: TextOrInteger + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data Enumeration = Enumeration + { name :: Text + , type_ :: Type + , values :: [EnumerationEntry] + , supportsCustomValues :: Maybe Bool + , documentation :: Maybe Text + , since :: Maybe Text + , proposed :: Maybe Bool + } + deriving (Show, Eq, Ord) + +data MetaData = MetaData + { version :: Text + } + deriving (Show, Eq, Ord) + +data MetaModel = MetaModel + { metaData :: MetaData + , requests :: [Request] + , notifications :: [Notification] + , structures :: [Structure] + , enumerations :: [Enumeration] + , typeAliases :: [TypeAlias] + } + deriving (Show, Eq, Ord) + +-- We need to do some massaging to make sure that we get the right aeson instances for +-- these types and can actually parse the incoming data! +$( + let + -- "type" is very common, we use "type_" on the Haskell side + defOpts = defaultOptions{fieldLabelModifier = \case { "type_" -> "type"; x -> x; }} + + propertyInst = JSON.deriveJSON defOpts ''Property + slInst = JSON.deriveJSON defOpts ''StructureLiteral + + -- 'BaseType' is a union of strings, so we encode it as an untagged sum with some + -- mangling of the constructor names + baseTyNameToTag :: String -> String + baseTyNameToTag = \case + "Integer" -> "integer" + "UInteger" -> "uinteger" + "Decimal" -> "decimal" + "String" -> "string" + "Boolean" -> "boolean" + "Null" -> "null" + x -> x + baseTyNameInst = JSON.deriveJSON (defOpts{sumEncoding=JSON.UntaggedValue, constructorTagModifier=baseTyNameToTag}) ''BaseTypeName + + -- 'Type' is a *tagged* union, but the tag is a string field (sigh), fortunately + -- aeson can deal with this. Also needs some constructor mangling. + typeToTag :: String -> String + typeToTag = \case + "BaseType" -> "base" + "ReferenceType" -> "reference" + "ArrayType" -> "array" + "MapType" -> "map" + "AndType" -> "and" + "OrType" -> "or" + "TupleType" -> "tuple" + "StructureLiteralType" -> "literal" + "StringLiteralType" -> "stringLiteral" + "IntegerLiteralType" -> "integerLiteral" + "BooleanLiteralType" -> "booleanLiteral" + x -> x + typeOpts = defOpts + { sumEncoding=JSON.defaultTaggedObject{tagFieldName="kind"} + , constructorTagModifier=typeToTag + , fieldLabelModifier= \s -> over _head Char.toLower $ Prelude.dropWhile Char.isLower s + } + typeInst = JSON.deriveJSON typeOpts ''Type + + -- The rest are mostly normal + reqInst = JSON.deriveJSON defOpts ''Request + notInst = JSON.deriveJSON defOpts ''Notification + sInst = JSON.deriveJSON defOpts ''Structure + taInst = JSON.deriveJSON defOpts ''TypeAlias + -- TextOrInteger is also an untagged sum + tiInst = JSON.deriveJSON (defOpts{sumEncoding=UntaggedValue}) ''TextOrInteger + eeInst = JSON.deriveJSON defOpts ''EnumerationEntry + eInst = JSON.deriveJSON defOpts ''Enumeration + mdInst = JSON.deriveJSON defOpts ''MetaData + mmInst = JSON.deriveJSON defOpts ''MetaModel + in mconcat <$> sequence [ propertyInst, slInst, baseTyNameInst, typeInst, reqInst, notInst, sInst, taInst, tiInst, eeInst, eInst, mdInst, mmInst ] + ) + diff --git a/lsp-types/src/Language/LSP/Types.hs b/lsp-types/src/Language/LSP/Types.hs index 4c4975765..1adcb0c7a 100644 --- a/lsp-types/src/Language/LSP/Types.hs +++ b/lsp-types/src/Language/LSP/Types.hs @@ -1,72 +1,28 @@ module Language.LSP.Types - ( module Language.LSP.Types.CallHierarchy - , module Language.LSP.Types.Cancellation - , module Language.LSP.Types.CodeAction - , module Language.LSP.Types.CodeLens - , module Language.LSP.Types.Command + ( + module Language.LSP.Types.CodeAction , module Language.LSP.Types.Common - , module Language.LSP.Types.Completion - , module Language.LSP.Types.Configuration - , module Language.LSP.Types.Declaration - , module Language.LSP.Types.Definition - , module Language.LSP.Types.Diagnostic - , module Language.LSP.Types.DocumentColor - , module Language.LSP.Types.DocumentFilter - , module Language.LSP.Types.DocumentHighlight - , module Language.LSP.Types.DocumentLink - , module Language.LSP.Types.DocumentSymbol - , module Language.LSP.Types.FoldingRange - , module Language.LSP.Types.Formatting - , module Language.LSP.Types.Hover - , module Language.LSP.Types.Implementation - , module Language.LSP.Types.Initialize - , module Language.LSP.Types.Location + , module Language.LSP.Types.Internal.Generated + , module Language.LSP.Types.Internal.Lenses , module Language.LSP.Types.LspId + , module Language.LSP.Types.Location , module Language.LSP.Types.MarkupContent , module Language.LSP.Types.Method , module Language.LSP.Types.Message , module Language.LSP.Types.Parsing , module Language.LSP.Types.Progress - , module Language.LSP.Types.References , module Language.LSP.Types.Registration - , module Language.LSP.Types.Rename - , module Language.LSP.Types.SignatureHelp - , module Language.LSP.Types.StaticRegistrationOptions - , module Language.LSP.Types.SelectionRange , module Language.LSP.Types.SemanticTokens - , module Language.LSP.Types.TextDocument - , module Language.LSP.Types.TypeDefinition , module Language.LSP.Types.Uri , module Language.LSP.Types.Uri.OsPath - , module Language.LSP.Types.WatchedFiles - , module Language.LSP.Types.Window , module Language.LSP.Types.WorkspaceEdit - , module Language.LSP.Types.WorkspaceFolders - , module Language.LSP.Types.WorkspaceSymbol ) where -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.Cancellation import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.Command import Language.LSP.Types.Common -import Language.LSP.Types.Completion -import Language.LSP.Types.Configuration -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.Diagnostic -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.DocumentFilter -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation -import Language.LSP.Types.Initialize +import Language.LSP.Types.Internal.Generated +import Language.LSP.Types.Internal.Lenses import Language.LSP.Types.Location import Language.LSP.Types.LspId import Language.LSP.Types.MarkupContent @@ -74,19 +30,8 @@ import Language.LSP.Types.Message import Language.LSP.Types.Method import Language.LSP.Types.Parsing import Language.LSP.Types.Progress -import Language.LSP.Types.References import Language.LSP.Types.Registration -import Language.LSP.Types.Rename -import Language.LSP.Types.SelectionRange import Language.LSP.Types.SemanticTokens -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition import Language.LSP.Types.Uri import Language.LSP.Types.Uri.OsPath -import Language.LSP.Types.WatchedFiles -import Language.LSP.Types.Window import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types.WorkspaceFolders -import Language.LSP.Types.WorkspaceSymbol diff --git a/lsp-types/src/Language/LSP/Types/CallHierarchy.hs b/lsp-types/src/Language/LSP/Types/CallHierarchy.hs deleted file mode 100644 index d627ca1a6..000000000 --- a/lsp-types/src/Language/LSP/Types/CallHierarchy.hs +++ /dev/null @@ -1,100 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -{- | Since LSP 3.16.0 -} -module Language.LSP.Types.CallHierarchy where - -import Data.Aeson.TH -import Data.Aeson.Types ( Value ) -import Data.Text ( Text ) - -import Language.LSP.Types.Common -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils - - -data CallHierarchyClientCapabilities = - CallHierarchyClientCapabilities - { _dynamicRegistration :: Maybe Bool } - deriving (Show, Read, Eq) -deriveJSON lspOptions ''CallHierarchyClientCapabilities - -makeExtendingDatatype "CallHierarchyOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''CallHierarchyOptions - -makeExtendingDatatype "CallHierarchyRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''CallHierarchyOptions - , ''StaticRegistrationOptions - ] - [] -deriveJSON lspOptions ''CallHierarchyRegistrationOptions - -makeExtendingDatatype "CallHierarchyPrepareParams" - [''TextDocumentPositionParams, ''WorkDoneProgressParams] [] -deriveJSON lspOptions ''CallHierarchyPrepareParams - -data CallHierarchyItem = - CallHierarchyItem - { _name :: Text - , _kind :: SymbolKind - , _tags :: Maybe (List SymbolTag) - -- | More detail for this item, e.g. the signature of a function. - , _detail :: Maybe Text - , _uri :: Uri - , _range :: Range - -- | The range that should be selected and revealed when this symbol - -- is being picked, e.g. the name of a function. Must be contained by - -- the @_range@. - , _selectionRange :: Range - -- | A data entry field that is preserved between a call hierarchy - -- prepare and incoming calls or outgoing calls requests. - , _xdata :: Maybe Value - } - deriving (Show, Read, Eq, Ord) -deriveJSON lspOptions ''CallHierarchyItem - --- ------------------------------------- - -makeExtendingDatatype "CallHierarchyIncomingCallsParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_item", [t| CallHierarchyItem |])] -deriveJSON lspOptions ''CallHierarchyIncomingCallsParams - -data CallHierarchyIncomingCall = - CallHierarchyIncomingCall - { -- | The item that makes the call. - _from :: CallHierarchyItem - -- | The ranges at which the calls appear. This is relative to the caller - -- denoted by @_from@. - , _fromRanges :: List Range - } - deriving (Show, Read, Eq, Ord) -deriveJSON lspOptions ''CallHierarchyIncomingCall - --- ------------------------------------- - -makeExtendingDatatype "CallHierarchyOutgoingCallsParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_item", [t| CallHierarchyItem |])] -deriveJSON lspOptions ''CallHierarchyOutgoingCallsParams - -data CallHierarchyOutgoingCall = - CallHierarchyOutgoingCall - { -- | The item that is called. - _to :: CallHierarchyItem - -- | The range at which this item is called. THis is the range relative to - -- the caller, e.g the item passed to `callHierarchy/outgoingCalls` request. - , _fromRanges :: List Range - } - deriving (Show, Read, Eq, Ord) -deriveJSON lspOptions ''CallHierarchyOutgoingCall diff --git a/lsp-types/src/Language/LSP/Types/Cancellation.hs b/lsp-types/src/Language/LSP/Types/Cancellation.hs deleted file mode 100644 index eec4043b6..000000000 --- a/lsp-types/src/Language/LSP/Types/Cancellation.hs +++ /dev/null @@ -1,28 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE PolyKinds #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE ExistentialQuantification #-} -module Language.LSP.Types.Cancellation where - -import Data.Aeson.TH -import Language.LSP.Types.LspId -import Language.LSP.Types.Utils - -data CancelParams = forall m. - CancelParams - { -- | The request id to cancel. - _id :: LspId m - } - -deriving instance Read CancelParams -deriving instance Show CancelParams -instance Eq CancelParams where - (CancelParams a) == CancelParams b = - case (a,b) of - (IdInt x, IdInt y) -> x == y - (IdString x, IdString y) -> x == y - _ -> False - -deriveJSON lspOptions ''CancelParams diff --git a/lsp-types/src/Language/LSP/Types/Capabilities.hs b/lsp-types/src/Language/LSP/Types/Capabilities.hs index f20817ed2..2c572b084 100644 --- a/lsp-types/src/Language/LSP/Types/Capabilities.hs +++ b/lsp-types/src/Language/LSP/Types/Capabilities.hs @@ -1,19 +1,24 @@ -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE OverloadedLabels #-} +{-# LANGUAGE OverloadedStrings #-} module Language.LSP.Types.Capabilities ( - module Language.LSP.Types.ClientCapabilities - , module Language.LSP.Types.ServerCapabilities - , module Language.LSP.Types.WorkspaceEdit - , fullCaps + fullCaps , LSPVersion(..) , capsForVersion ) where -import Prelude hiding (min) -import Language.LSP.Types.ClientCapabilities -import Language.LSP.Types.ServerCapabilities -import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types +import Data.Row +import Language.LSP.Types.Common +import Language.LSP.Types.CodeAction +import Language.LSP.Types.SemanticTokens +import Language.LSP.Types.Internal.Generated +import Prelude hiding (min) + +{- +TODO: this is out-of-date/needs an audit +TODO: can we generate this? process the 'since' annotations in the metamodel? +-} -- | Capabilities for full conformance to the current (v3.15) LSP specification. fullCaps :: ClientCapabilities @@ -35,241 +40,249 @@ data LSPVersion = LSPVersion Int Int -- ^ Construct a major.minor version -- * 3.4 extended completion item and symbol item kinds -- * 3.0 dynamic registration capsForVersion :: LSPVersion -> ClientCapabilities -capsForVersion (LSPVersion maj min) = ClientCapabilities (Just w) (Just td) (Just window) (since 3 16 general) Nothing +capsForVersion (LSPVersion maj min) = caps where - w = WorkspaceClientCapabilities - (Just True) - (Just (WorkspaceEditClientCapabilities + caps = ClientCapabilities { + _workspace=Just w + , _textDocument=Just td + , _window=Just window + , _general=since 3 16 general + , _experimental=Nothing + -- TODO + , _notebookDocument=Nothing + } + w = WorkspaceClientCapabilities { + _applyEdit = Just True + , _workspaceEdit = Just (WorkspaceEditClientCapabilities (Just True) (since 3 13 resourceOperations) Nothing (since 3 16 True) - (since 3 16 (WorkspaceEditChangeAnnotationClientCapabilities (Just True))))) - (Just (DidChangeConfigurationClientCapabilities dynamicReg)) - (Just (DidChangeWatchedFilesClientCapabilities dynamicReg)) - (Just symbolCapabilities) - (Just (ExecuteCommandClientCapabilities dynamicReg)) - (since 3 6 True) - (since 3 6 True) - (since 3 16 (SemanticTokensWorkspaceClientCapabilities $ Just True)) - - resourceOperations = List - [ ResourceOperationCreate - , ResourceOperationDelete - , ResourceOperationRename + (since 3 16 (#groupsOnLabel .== Just True))) + , _didChangeConfiguration = Just (DidChangeConfigurationClientCapabilities dynamicReg) + , _didChangeWatchedFiles = Just (DidChangeWatchedFilesClientCapabilities dynamicReg (Just True)) + , _symbol = Just symbolCapabilities + , _executeCommand = Just (ExecuteCommandClientCapabilities dynamicReg) + , _workspaceFolders = since 3 6 True + , _configuration = since 3 6 True + , _semanticTokens = since 3 16 (SemanticTokensWorkspaceClientCapabilities $ Just True) + -- TODO + , _codeLens = Nothing + , _fileOperations = Nothing + , _inlineValue = Nothing + , _inlayHint = Nothing + , _diagnostics = Nothing + } + + resourceOperations = + [ ResourceOperationKind_Create + , ResourceOperationKind_Delete + , ResourceOperationKind_Rename ] symbolCapabilities = WorkspaceSymbolClientCapabilities dynamicReg - (since 3 4 symbolKindCapabilities) - (since 3 16 symbolTagCapabilities) - - symbolKindCapabilities = - WorkspaceSymbolKindClientCapabilities (Just sKs) - - symbolTagCapabilities = - WorkspaceSymbolTagClientCapabilities (Just (List [StDeprecated])) + (since 3 4 (#valueSet .== Just sKs)) + (since 3 16 (#valueSet .== [SymbolTag_Deprecated])) + (since 3 17 (#properties .== [])) sKs - | maj >= 3 && min >= 4 = List (oldSKs ++ newSKs) - | otherwise = List oldSKs - - oldSKs = [ SkFile - , SkModule - , SkNamespace - , SkPackage - , SkClass - , SkMethod - , SkProperty - , SkField - , SkConstructor - , SkEnum - , SkInterface - , SkFunction - , SkVariable - , SkConstant - , SkString - , SkNumber - , SkBoolean - , SkArray + | maj >= 3 && min >= 4 = oldSKs ++ newSKs + | otherwise = oldSKs + + oldSKs = [ SymbolKind_File + , SymbolKind_Module + , SymbolKind_Namespace + , SymbolKind_Package + , SymbolKind_Class + , SymbolKind_Method + , SymbolKind_Property + , SymbolKind_Field + , SymbolKind_Constructor + , SymbolKind_Enum + , SymbolKind_Interface + , SymbolKind_Function + , SymbolKind_Variable + , SymbolKind_Constant + , SymbolKind_String + , SymbolKind_Number + , SymbolKind_Boolean + , SymbolKind_Array ] - newSKs = [ SkObject - , SkKey - , SkNull - , SkEnumMember - , SkStruct - , SkEvent - , SkOperator - , SkTypeParameter + newSKs = [ SymbolKind_Object + , SymbolKind_Key + , SymbolKind_Null + , SymbolKind_EnumMember + , SymbolKind_Struct + , SymbolKind_Event + , SymbolKind_Operator + , SymbolKind_TypeParameter ] -- Only one token format for now, just list it here - tfs = List [ TokenFormatRelative ] - - semanticTokensCapabilities = SemanticTokensClientCapabilities - (Just True) - (SemanticTokensRequestsClientCapabilities - (Just $ SemanticTokensRangeBool True) - (Just (SemanticTokensFullDelta (SemanticTokensDeltaClientCapabilities $ Just True)))) - (List knownSemanticTokenTypes) - (List knownSemanticTokenModifiers) - tfs - (Just True) - (Just True) - - td = TextDocumentClientCapabilities - (Just sync) - (Just completionCapability) - (Just hoverCapability) - (Just signatureHelpCapability) - (Just (ReferencesClientCapabilities dynamicReg)) - (Just (DocumentHighlightClientCapabilities dynamicReg)) - (Just documentSymbolCapability) - (Just (DocumentFormattingClientCapabilities dynamicReg)) - (Just (DocumentRangeFormattingClientCapabilities dynamicReg)) - (Just (DocumentOnTypeFormattingClientCapabilities dynamicReg)) - (since 3 14 (DeclarationClientCapabilities dynamicReg (Just True))) - (Just (DefinitionClientCapabilities dynamicReg (since 3 14 True))) - (since 3 6 (TypeDefinitionClientCapabilities dynamicReg (since 3 14 True))) - (since 3 6 (ImplementationClientCapabilities dynamicReg (since 3 14 True))) - (Just codeActionCapability) - (Just (CodeLensClientCapabilities dynamicReg)) - (Just (DocumentLinkClientCapabilities dynamicReg (since 3 15 True))) - (since 3 6 (DocumentColorClientCapabilities dynamicReg)) - (Just (RenameClientCapabilities dynamicReg (since 3 12 True) (since 3 16 PsIdentifier) (since 3 16 True))) - (Just publishDiagnosticsCapabilities) - (since 3 10 foldingRangeCapability) - (since 3 5 (SelectionRangeClientCapabilities dynamicReg)) - (since 3 16 (CallHierarchyClientCapabilities dynamicReg)) - (since 3 16 semanticTokensCapabilities) + tfs = [ TokenFormat_Relative ] + + semanticTokensCapabilities = SemanticTokensClientCapabilities { + _dynamicRegistration=Just True + , _requests= #range .== Just (InL True) .+ #full .== Just (InR (#delta .== Just True)) + , _tokenTypes=fmap semanticTokenTypesToValue knownSemanticTokenTypes + , _tokenModifiers=fmap semanticTokenModifiersToValue knownSemanticTokenModifiers + , _formats=tfs + , _overlappingTokenSupport=Just True + , _multilineTokenSupport=Just True + , _serverCancelSupport=Just True + , _augmentsSyntaxTokens=Just True + } + + td = TextDocumentClientCapabilities { + _synchronization=Just sync + , _completion=Just completionCapability + , _hover=Just hoverCapability + , _signatureHelp=Just signatureHelpCapability + , _references=Just (ReferenceClientCapabilities dynamicReg) + , _documentHighlight=Just (DocumentHighlightClientCapabilities dynamicReg) + , _documentSymbol=Just documentSymbolCapability + , _formatting=Just (DocumentFormattingClientCapabilities dynamicReg) + , _rangeFormatting=Just (DocumentRangeFormattingClientCapabilities dynamicReg) + , _onTypeFormatting=Just (DocumentOnTypeFormattingClientCapabilities dynamicReg) + , _declaration=since 3 14 (DeclarationClientCapabilities dynamicReg (Just True)) + , _definition=Just (DefinitionClientCapabilities dynamicReg (since 3 14 True)) + , _typeDefinition=since 3 6 (TypeDefinitionClientCapabilities dynamicReg (since 3 14 True)) + , _implementation=since 3 6 (ImplementationClientCapabilities dynamicReg (since 3 14 True)) + , _codeAction=Just codeActionCapability + , _codeLens=Just (CodeLensClientCapabilities dynamicReg) + , _documentLink=Just (DocumentLinkClientCapabilities dynamicReg (since 3 15 True)) + , _colorProvider=since 3 6 (DocumentColorClientCapabilities dynamicReg) + , _rename=Just (RenameClientCapabilities dynamicReg (since 3 12 True) (since 3 16 PrepareSupportDefaultBehavior_Identifier) (since 3 16 True)) + , _publishDiagnostics=Just publishDiagnosticsCapabilities + , _foldingRange=since 3 10 foldingRangeCapability + , _selectionRange=since 3 5 (SelectionRangeClientCapabilities dynamicReg) + , _callHierarchy=since 3 16 (CallHierarchyClientCapabilities dynamicReg) + , _semanticTokens=since 3 16 semanticTokensCapabilities + -- TODO + , _linkedEditingRange=Nothing + , _moniker=Nothing + , _typeHierarchy=Nothing + , _inlineValue=Nothing + , _inlayHint=Nothing + , _diagnostic=Nothing + } sync = - TextDocumentSyncClientCapabilities - dynamicReg - (Just True) - (Just True) - (Just True) + TextDocumentSyncClientCapabilities { + _dynamicRegistration=dynamicReg + , _willSave=Just True + , _willSaveWaitUntil=Just True + , _didSave=Just True + } completionCapability = - CompletionClientCapabilities - dynamicReg - (Just completionItemCapabilities) - (since 3 4 completionItemKindCapabilities) - (since 3 3 True) - - completionItemCapabilities = CompletionItemClientCapabilities - (Just True) - (Just True) - (since 3 3 (List [MkPlainText, MkMarkdown])) - (Just True) - (since 3 9 True) - (since 3 15 completionItemTagsCapabilities) - (since 3 16 True) - (since 3 16 (CompletionItemResolveClientCapabilities (List ["documentation", "details"]))) - (since 3 16 (CompletionItemInsertTextModeClientCapabilities (List []))) - - completionItemKindCapabilities = - CompletionItemKindClientCapabilities (Just ciKs) - - completionItemTagsCapabilities = - CompletionItemTagsClientCapabilities (List [ CitDeprecated ]) + CompletionClientCapabilities{ + _dynamicRegistration=dynamicReg + , _completionItem=Just completionItemCapabilities + , _completionItemKind=since 3 4 (#valueSet .== Just ciKs) + , _insertTextMode=since 3 17 InsertTextMode_AsIs + , _contextSupport=since 3 3 True + , _completionList=since 3 17 (#itemDefaults .== Just []) + } + + completionItemCapabilities = + #snippetSupport .== Just True + .+ #commitCharactersSupport .== Just True + .+ #documentationFormat .== since 3 3 allMarkups + .+ #deprecatedSupport .== Just True + .+ #preselectSupport .== since 3 9 True + .+ #tagSupport .== since 3 15 (#valueSet .== []) + .+ #insertReplaceSupport .== since 3 16 True + .+ #resolveSupport .== since 3 16 (#properties .== ["documentation", "details"]) + .+ #insertTextModeSupport .== since 3 16 (#valueSet .== []) + .+ #labelDetailsSupport .== since 3 17 True ciKs - | maj >= 3 && min >= 4 = List (oldCiKs ++ newCiKs) - | otherwise = List oldCiKs - - oldCiKs = [ CiText - , CiMethod - , CiFunction - , CiConstructor - , CiField - , CiVariable - , CiClass - , CiInterface - , CiModule - , CiProperty - , CiUnit - , CiValue - , CiEnum - , CiKeyword - , CiSnippet - , CiColor - , CiFile - , CiReference + | maj >= 3 && min >= 4 = oldCiKs ++ newCiKs + | otherwise = oldCiKs + + oldCiKs = [ CompletionItemKind_Text + , CompletionItemKind_Method + , CompletionItemKind_Function + , CompletionItemKind_Constructor + , CompletionItemKind_Field + , CompletionItemKind_Variable + , CompletionItemKind_Class + , CompletionItemKind_Interface + , CompletionItemKind_Module + , CompletionItemKind_Property + , CompletionItemKind_Unit + , CompletionItemKind_Value + , CompletionItemKind_Enum + , CompletionItemKind_Keyword + , CompletionItemKind_Snippet + , CompletionItemKind_Color + , CompletionItemKind_File + , CompletionItemKind_Reference ] - newCiKs = [ CiFolder - , CiEnumMember - , CiConstant - , CiStruct - , CiEvent - , CiOperator - , CiTypeParameter + newCiKs = [ CompletionItemKind_Folder + , CompletionItemKind_EnumMember + , CompletionItemKind_Constant + , CompletionItemKind_Struct + , CompletionItemKind_Event + , CompletionItemKind_Operator + , CompletionItemKind_TypeParameter ] hoverCapability = - HoverClientCapabilities - dynamicReg - (since 3 3 (List [MkPlainText, MkMarkdown])) + HoverClientCapabilities { + _dynamicRegistration=dynamicReg + , _contentFormat=since 3 3 allMarkups + } codeActionCapability - = CodeActionClientCapabilities - dynamicReg - (since 3 8 (CodeActionLiteralSupport caKs)) - (since 3 15 True) - (since 3 16 True) - (since 3 16 True) - (since 3 16 (CodeActionResolveClientCapabilities (List []))) - (since 3 16 True) - caKs = CodeActionKindClientCapabilities - (List specCodeActionKinds) + = CodeActionClientCapabilities { + _dynamicRegistration=dynamicReg + , _codeActionLiteralSupport=since 3 8 (#codeActionKind .== (#valueSet .== specCodeActionKinds)) + , _isPreferredSupport=since 3 15 True + , _disabledSupport=since 3 16 True + , _dataSupport=since 3 16 True + , _resolveSupport=since 3 16 (#properties .== []) + , _honorsChangeAnnotations=since 3 16 True + } signatureHelpCapability = - SignatureHelpClientCapabilities - dynamicReg - (Just signatureInformationCapability) - Nothing - - signatureInformationCapability = - SignatureHelpSignatureInformation - (Just (List [MkPlainText, MkMarkdown])) - (Just signatureParameterCapability) - (since 3 16 True) - - signatureParameterCapability = - SignatureHelpParameterInformation (since 3 14 True) + SignatureHelpClientCapabilities { + _dynamicRegistration=dynamicReg + , _signatureInformation=Just (#documentationFormat .== Just allMarkups .+ #parameterInformation .== Just (#labelOffsetSupport .== Just True) .+ #activeParameterSupport .== Just True) + , _contextSupport=since 3 16 True + } documentSymbolCapability = - DocumentSymbolClientCapabilities - dynamicReg - (since 3 4 documentSymbolKind) - (since 3 10 True) - (since 3 16 documentSymbolTag) - (since 3 16 True) - - documentSymbolKind = - DocumentSymbolKindClientCapabilities - (Just sKs) -- same as workspace symbol kinds - - documentSymbolTag = - DocumentSymbolTagClientCapabilities (Just (List [StDeprecated])) + DocumentSymbolClientCapabilities { + _dynamicRegistration=dynamicReg + -- same as workspace symbol kinds + , _symbolKind=Just (#valueSet .== Just sKs) + , _hierarchicalDocumentSymbolSupport=since 3 10 True + , _tagSupport=since 3 16 (#valueSet .== [SymbolTag_Deprecated]) + , _labelSupport=since 3 16 True + } foldingRangeCapability = - FoldingRangeClientCapabilities - dynamicReg - Nothing - (Just False) + FoldingRangeClientCapabilities { + _dynamicRegistration=dynamicReg + , _rangeLimit=Nothing + , _lineFoldingOnly=Nothing + , _foldingRangeKind=since 3 17 (#valueSet .== Just []) + , _foldingRange=since 3 16 (#collapsedText .== Just True) + } publishDiagnosticsCapabilities = - PublishDiagnosticsClientCapabilities - (since 3 7 True) - (since 3 15 publishDiagnosticsTagsCapabilities) - (since 3 15 True) - - publishDiagnosticsTagsCapabilities = - PublishDiagnosticsTagsClientCapabilities - (List [ DtUnnecessary, DtDeprecated ]) + PublishDiagnosticsClientCapabilities { + _relatedInformation=since 3 7 True + , _tagSupport=since 3 15 (#valueSet .== [ DiagnosticTag_Unnecessary, DiagnosticTag_Deprecated ]) + , _versionSupport=since 3 15 True + , _codeDescriptionSupport=since 3 16 True + , _dataSupport=since 3 16 True + } dynamicReg | maj >= 3 = Just True @@ -279,12 +292,18 @@ capsForVersion (LSPVersion maj min) = ClientCapabilities (Just w) (Just td) (Jus | otherwise = Nothing window = - WindowClientCapabilities - (since 3 15 True) - (since 3 16 $ ShowMessageRequestClientCapabilities Nothing) - (since 3 16 $ ShowDocumentClientCapabilities True) - - general = GeneralClientCapabilities - (since 3 16 $ StaleRequestClientCapabilities True (List [])) - (since 3 16 $ RegularExpressionsClientCapabilities "" Nothing) - (since 3 16 $ MarkdownClientCapabilities "" Nothing) + WindowClientCapabilities { + _workDoneProgress=since 3 15 True + , _showMessage=since 3 16 $ ShowMessageRequestClientCapabilities Nothing + , _showDocument=since 3 16 $ ShowDocumentClientCapabilities True + } + + general = GeneralClientCapabilities { + _staleRequestSupport=since 3 16 (#cancel .== True .+ #retryOnContentModified .== []) + , _regularExpressions=since 3 16 $ RegularExpressionsClientCapabilities "" Nothing + , _markdown=since 3 16 $ MarkdownClientCapabilities "" Nothing (Just []) + -- TODO + , _positionEncodings=Nothing + } + + allMarkups = [MarkupKind_PlainText, MarkupKind_Markdown] diff --git a/lsp-types/src/Language/LSP/Types/ClientCapabilities.hs b/lsp-types/src/Language/LSP/Types/ClientCapabilities.hs deleted file mode 100644 index 7c1288959..000000000 --- a/lsp-types/src/Language/LSP/Types/ClientCapabilities.hs +++ /dev/null @@ -1,295 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.ClientCapabilities where - -import Data.Aeson.TH -import qualified Data.Aeson as A -import Data.Default -import Data.Text (Text) - -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.Command -import Language.LSP.Types.Completion -import Language.LSP.Types.Configuration -import Language.LSP.Types.Diagnostic -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation -import Language.LSP.Types.References -import Language.LSP.Types.Rename -import Language.LSP.Types.SelectionRange -import Language.LSP.Types.SemanticTokens -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition -import Language.LSP.Types.Utils -import Language.LSP.Types.WatchedFiles -import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types.WorkspaceSymbol -import Language.LSP.Types.MarkupContent (MarkdownClientCapabilities) -import Language.LSP.Types.Common (List) - - -data WorkspaceClientCapabilities = - WorkspaceClientCapabilities - { -- | The client supports applying batch edits to the workspace by supporting - -- the request 'workspace/applyEdit' - _applyEdit :: Maybe Bool - - -- | Capabilities specific to `WorkspaceEdit`s - , _workspaceEdit :: Maybe WorkspaceEditClientCapabilities - - -- | Capabilities specific to the `workspace/didChangeConfiguration` notification. - , _didChangeConfiguration :: Maybe DidChangeConfigurationClientCapabilities - - -- | Capabilities specific to the `workspace/didChangeWatchedFiles` notification. - , _didChangeWatchedFiles :: Maybe DidChangeWatchedFilesClientCapabilities - - -- | Capabilities specific to the `workspace/symbol` request. - , _symbol :: Maybe WorkspaceSymbolClientCapabilities - - -- | Capabilities specific to the `workspace/executeCommand` request. - , _executeCommand :: Maybe ExecuteCommandClientCapabilities - - -- | The client has support for workspace folders. - , _workspaceFolders :: Maybe Bool - - -- | The client supports `workspace/configuration` requests. - , _configuration :: Maybe Bool - - -- | Capabilities specific to the semantic token requests scoped to the - -- workspace. - -- - -- @since 3.16.0 - , _semanticTokens :: Maybe SemanticTokensWorkspaceClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceClientCapabilities - -instance Default WorkspaceClientCapabilities where - def = WorkspaceClientCapabilities def def def def def def def def def - --- ------------------------------------- - -data TextDocumentClientCapabilities = - TextDocumentClientCapabilities - { _synchronization :: Maybe TextDocumentSyncClientCapabilities - - -- | Capabilities specific to the `textDocument/completion` - , _completion :: Maybe CompletionClientCapabilities - - -- | Capabilities specific to the `textDocument/hover` - , _hover :: Maybe HoverClientCapabilities - - -- | Capabilities specific to the `textDocument/signatureHelp` - , _signatureHelp :: Maybe SignatureHelpClientCapabilities - - -- | Capabilities specific to the `textDocument/references` - , _references :: Maybe ReferencesClientCapabilities - - -- | Capabilities specific to the `textDocument/documentHighlight` - , _documentHighlight :: Maybe DocumentHighlightClientCapabilities - - -- | Capabilities specific to the `textDocument/documentSymbol` - , _documentSymbol :: Maybe DocumentSymbolClientCapabilities - - -- | Capabilities specific to the `textDocument/formatting` - , _formatting :: Maybe DocumentFormattingClientCapabilities - - -- | Capabilities specific to the `textDocument/rangeFormatting` - , _rangeFormatting :: Maybe DocumentRangeFormattingClientCapabilities - - -- | Capabilities specific to the `textDocument/onTypeFormatting` - , _onTypeFormatting :: Maybe DocumentOnTypeFormattingClientCapabilities - - -- | Capabilities specific to the `textDocument/declaration` request. - -- - -- Since LSP 3.14.0 - , _declaration :: Maybe DeclarationClientCapabilities - - -- | Capabilities specific to the `textDocument/definition` - , _definition :: Maybe DefinitionClientCapabilities - - -- | Capabilities specific to the `textDocument/typeDefinition` - , _typeDefinition :: Maybe TypeDefinitionClientCapabilities - - -- | Capabilities specific to the `textDocument/implementation` - , _implementation :: Maybe ImplementationClientCapabilities - - -- | Capabilities specific to the `textDocument/codeAction` - , _codeAction :: Maybe CodeActionClientCapabilities - - -- | Capabilities specific to the `textDocument/codeLens` - , _codeLens :: Maybe CodeLensClientCapabilities - - -- | Capabilities specific to the `textDocument/documentLink` - , _documentLink :: Maybe DocumentLinkClientCapabilities - - -- | Capabilities specific to the `textDocument/documentColor` and the - -- `textDocument/colorPresentation` request - , _colorProvider :: Maybe DocumentColorClientCapabilities - - -- | Capabilities specific to the `textDocument/rename` - , _rename :: Maybe RenameClientCapabilities - - -- | Capabilities specific to `textDocument/publishDiagnostics` - , _publishDiagnostics :: Maybe PublishDiagnosticsClientCapabilities - - -- | Capabilities specific to the `textDocument/foldingRange` request. - -- Since LSP 3.10. - -- - -- @since 0.7.0.0 - , _foldingRange :: Maybe FoldingRangeClientCapabilities - - -- | Capabilities specific to the `textDocument/selectionRange` request. - -- Since LSP 3.15.0 - , _selectionRange :: Maybe SelectionRangeClientCapabilities - - -- | Call hierarchy specific to the `textDocument/prepareCallHierarchy` request. - -- Since LSP 3.16.0 - , _callHierarchy :: Maybe CallHierarchyClientCapabilities - - -- | Capabilities specific to the various semantic token requests. - -- - -- @since 3.16.0 - , _semanticTokens :: Maybe SemanticTokensClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentClientCapabilities - -instance Default TextDocumentClientCapabilities where - def = TextDocumentClientCapabilities def def def def def def def def - def def def def def def def def - def def def def def def def def - --- --------------------------------------------------------------------- - --- | Capabilities specific to the `MessageActionItem` type. -data MessageActionItemClientCapabilities = - MessageActionItemClientCapabilities - { - -- | Whether the client supports additional attributes which - -- are preserved and sent back to the server in the - -- request's response. - _additionalPropertiesSupport :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''MessageActionItemClientCapabilities - --- | Show message request client capabilities -data ShowMessageRequestClientCapabilities = - ShowMessageRequestClientCapabilities - { -- | Capabilities specific to the `MessageActionItem` type. - _messageActionItem :: Maybe MessageActionItemClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ShowMessageRequestClientCapabilities - --- | Client capabilities for the show document request. --- --- @since 3.16.0 -data ShowDocumentClientCapabilities = - ShowDocumentClientCapabilities - { -- | The client has support for the show document request - _support :: Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ShowDocumentClientCapabilities - --- | Window specific client capabilities. -data WindowClientCapabilities = - WindowClientCapabilities - { -- | Whether client supports handling progress notifications. - -- - -- @since 3.15.0 - _workDoneProgress :: Maybe Bool - -- | Capabilities specific to the showMessage request - -- - -- @since 3.16.0 - , _showMessage :: Maybe ShowMessageRequestClientCapabilities - -- | Capabilities specific to the showDocument request - -- - -- @since 3.16.0 - , _showDocument :: Maybe ShowDocumentClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WindowClientCapabilities - -instance Default WindowClientCapabilities where - def = WindowClientCapabilities def def def - --- --------------------------------------------------------------------- - --- | Client capability that signals how the client --- handles stale requests (e.g. a request --- for which the client will not process the response --- anymore since the information is outdated). --- @since 3.17.0 -data StaleRequestClientCapabilities = - StaleRequestClientCapabilities - { _cancel :: Bool - , _retryOnContentModified :: List Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''StaleRequestClientCapabilities - --- | Client capabilities specific to the used markdown parser. --- @since 3.16.0 -data RegularExpressionsClientCapabilities = - RegularExpressionsClientCapabilities - { _engine :: Text - , _version :: Maybe Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''RegularExpressionsClientCapabilities - --- | General client capabilities. --- @since 3.16.0 -data GeneralClientCapabilities = - GeneralClientCapabilities - { - _staleRequestSupport :: Maybe StaleRequestClientCapabilities - -- | Client capabilities specific to regular expressions. - -- @since 3.16.0 - , _regularExpressions :: Maybe RegularExpressionsClientCapabilities - -- | Client capabilities specific to the client's markdown parser. - -- @since 3.16.0 - , _markdown :: Maybe MarkdownClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''GeneralClientCapabilities - -instance Default GeneralClientCapabilities where - def = GeneralClientCapabilities def def def - --- --------------------------------------------------------------------- - -data ClientCapabilities = - ClientCapabilities - { -- | Workspace specific client capabilities - _workspace :: Maybe WorkspaceClientCapabilities - -- | Text document specific client capabilities - , _textDocument :: Maybe TextDocumentClientCapabilities - -- | Window specific client capabilities. - , _window :: Maybe WindowClientCapabilities - -- | General client capabilities. - -- @since 3.16.0 - , _general :: Maybe GeneralClientCapabilities - -- | Experimental client capabilities. - , _experimental :: Maybe A.Object - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ClientCapabilities - -instance Default ClientCapabilities where - def = ClientCapabilities def def def def def diff --git a/lsp-types/src/Language/LSP/Types/CodeAction.hs b/lsp-types/src/Language/LSP/Types/CodeAction.hs index a59386922..0e9a7e49a 100644 --- a/lsp-types/src/Language/LSP/Types/CodeAction.hs +++ b/lsp-types/src/Language/LSP/Types/CodeAction.hs @@ -1,268 +1,60 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE OverloadedStrings #-} + +{-# OPTIONS_GHC -Wno-orphans #-} module Language.LSP.Types.CodeAction where -import Data.Aeson.TH -import Data.Aeson.Types -import Data.Default import Data.String -import Data.Text ( Text ) -import qualified Data.Text as T -import Language.LSP.Types.Command -import Language.LSP.Types.Diagnostic -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils -import Language.LSP.Types.WorkspaceEdit - - -data CodeActionKind - = -- | Empty kind. - CodeActionEmpty - | -- | Base kind for quickfix actions: @quickfix@. - CodeActionQuickFix - | -- | Base kind for refactoring actions: @refactor@. - CodeActionRefactor - | -- | Base kind for refactoring extraction actions: @refactor.extract@. - -- Example extract actions: - -- - -- - Extract method - -- - Extract function - -- - Extract variable - -- - Extract interface from class - -- - ... - CodeActionRefactorExtract - | -- | Base kind for refactoring inline actions: @refactor.inline@. - -- - -- Example inline actions: - -- - -- - Inline function - -- - Inline variable - -- - Inline constant - -- - ... - CodeActionRefactorInline - | -- | Base kind for refactoring rewrite actions: @refactor.rewrite@. - -- - -- Example rewrite actions: - -- - -- - Convert JavaScript function to class - -- - Add or remove parameter - -- - Encapsulate field - -- - Make method static - -- - Move method to base class - -- - ... - CodeActionRefactorRewrite - | -- | Base kind for source actions: @source@. - -- - -- Source code actions apply to the entire file. - CodeActionSource - | -- | Base kind for an organize imports source action: @source.organizeImports@. - CodeActionSourceOrganizeImports - | CodeActionUnknown Text - deriving (Read, Show, Eq) +import Data.Text (Text) +import qualified Data.Text as T +import Language.LSP.Types.Internal.Generated (CodeActionKind (..)) +-- | Convert a hierarchical string (e.g. "foo.bar") into a 'CodeActionKind'. fromHierarchicalString :: Text -> CodeActionKind fromHierarchicalString t = case t of - "" -> CodeActionEmpty - "quickfix" -> CodeActionQuickFix - "refactor" -> CodeActionRefactor - "refactor.extract" -> CodeActionRefactorExtract - "refactor.inline" -> CodeActionRefactorInline - "refactor.rewrite" -> CodeActionRefactorRewrite - "source" -> CodeActionSource - "source.organizeImports" -> CodeActionSourceOrganizeImports - s -> CodeActionUnknown s - + "" -> CodeActionKind_Empty + "quickfix" -> CodeActionKind_QuickFix + "refactor" -> CodeActionKind_Refactor + "refactor.extract" -> CodeActionKind_RefactorExtract + "refactor.inline" -> CodeActionKind_RefactorInline + "refactor.rewrite" -> CodeActionKind_RefactorRewrite + "source" -> CodeActionKind_Source + "source.organizeImports" -> CodeActionKind_SourceOrganizeImports + "source.fixAll" -> CodeActionKind_SourceFixAll + s -> CodeActionKind_Custom s + +-- | Convert a 'CodeActionKind' into a hierarchical string (e.g. "foo.bar"). toHierarchicalString :: CodeActionKind -> Text toHierarchicalString k = case k of - CodeActionEmpty -> "" - CodeActionQuickFix -> "quickfix" - CodeActionRefactor -> "refactor" - CodeActionRefactorExtract -> "refactor.extract" - CodeActionRefactorInline -> "refactor.inline" - CodeActionRefactorRewrite -> "refactor.rewrite" - CodeActionSource -> "source" - CodeActionSourceOrganizeImports -> "source.organizeImports" - (CodeActionUnknown s) -> s + CodeActionKind_Empty -> "" + CodeActionKind_QuickFix -> "quickfix" + CodeActionKind_Refactor -> "refactor" + CodeActionKind_RefactorExtract -> "refactor.extract" + CodeActionKind_RefactorInline -> "refactor.inline" + CodeActionKind_RefactorRewrite -> "refactor.rewrite" + CodeActionKind_Source -> "source" + CodeActionKind_SourceOrganizeImports -> "source.organizeImports" + CodeActionKind_SourceFixAll -> "source.fixAll" + (CodeActionKind_Custom s) -> s instance IsString CodeActionKind where fromString = fromHierarchicalString . T.pack -instance ToJSON CodeActionKind where - toJSON = String . toHierarchicalString - -instance FromJSON CodeActionKind where - parseJSON (String s) = pure $ fromHierarchicalString s - parseJSON _ = fail "CodeActionKind" - --- | Does the first 'CodeActionKind' subsume the other one, hierarchically. Reflexive. +-- | Does the first 'CodeActionKind' subsume the other one, hierarchically? Reflexive. codeActionKindSubsumes :: CodeActionKind -> CodeActionKind -> Bool -- Simple but ugly implementation: prefix on the string representation codeActionKindSubsumes parent child = toHierarchicalString parent `T.isPrefixOf` toHierarchicalString child +-- TODO: generate this kind of listing for all the 'open' enums. -- | The 'CodeActionKind's listed in the LSP spec specifically. specCodeActionKinds :: [CodeActionKind] specCodeActionKinds = [ - CodeActionQuickFix - , CodeActionRefactor - , CodeActionRefactorExtract - , CodeActionRefactorInline - , CodeActionRefactorRewrite - , CodeActionSource - , CodeActionSourceOrganizeImports - ] - --- ------------------------------------- - -data CodeActionKindClientCapabilities = - CodeActionKindClientCapabilities - { -- | The code action kind values the client supports. When this - -- property exists the client also guarantees that it will - -- handle values outside its set gracefully and falls back - -- to a default value when unknown. - _valueSet :: List CodeActionKind - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CodeActionKindClientCapabilities - -instance Default CodeActionKindClientCapabilities where - def = CodeActionKindClientCapabilities (List specCodeActionKinds) - -data CodeActionLiteralSupport = - CodeActionLiteralSupport - { _codeActionKind :: CodeActionKindClientCapabilities -- ^ The code action kind is support with the following value set. - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CodeActionLiteralSupport - -data CodeActionResolveClientCapabilities = - CodeActionResolveClientCapabilities - { _properties :: List Text -- ^ The properties that a client can resolve lazily. - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CodeActionResolveClientCapabilities - -data CodeActionClientCapabilities = CodeActionClientCapabilities - { -- | Whether code action supports dynamic registration. - _dynamicRegistration :: Maybe Bool, - -- | The client support code action literals as a valid response - -- of the `textDocument/codeAction` request. - -- Since 3.8.0 - _codeActionLiteralSupport :: Maybe CodeActionLiteralSupport, - -- | Whether code action supports the `isPreferred` property. Since LSP 3.15.0 - _isPreferredSupport :: Maybe Bool, - -- | Whether code action supports the `disabled` property. - -- - -- @since 3.16.0 - _disabledSupport :: Maybe Bool, - -- | Whether code action supports the `data` property which is - -- preserved between a `textDocument/codeAction` and a - -- `codeAction/resolve` request. - -- - -- @since 3.16.0 - _dataSupport :: Maybe Bool, - -- | Whether the client supports resolving additional code action - -- properties via a separate `codeAction/resolve` request. - -- - -- @since 3.16.0 - _resolveSupport :: Maybe CodeActionResolveClientCapabilities, - -- | Whether the client honors the change annotations in - -- text edits and resource operations returned via the - -- `CodeAction#edit` property by for example presenting - -- the workspace edit in the user interface and asking - -- for confirmation. - -- - -- @since 3.16.0 - _honorsChangeAnnotations :: Maybe Bool - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CodeActionClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "CodeActionOptions" [''WorkDoneProgressOptions] - [("_codeActionKinds", [t| Maybe (List CodeActionKind) |]), ("_resolveProvider", [t| Maybe Bool |]) ] -deriveJSON lspOptions ''CodeActionOptions - -makeExtendingDatatype "CodeActionRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''CodeActionOptions - ] [] -deriveJSON lspOptions ''CodeActionRegistrationOptions - --- ------------------------------------- - --- | Contains additional diagnostic information about the context in which a --- code action is run. -data CodeActionContext = CodeActionContext - { -- | An array of diagnostics known on the client side overlapping the range provided to the - -- @textDocument/codeAction@ request. They are provided so that the server knows which - -- errors are currently presented to the user for the given range. There is no guarantee - -- that these accurately reflect the error state of the resource. The primary parameter - -- to compute code actions is the provided range. - _diagnostics :: List Diagnostic - -- | Requested kind of actions to return. - -- - -- Actions not of this kind are filtered out by the client before being shown. So servers - -- can omit computing them. - , _only :: Maybe (List CodeActionKind) - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''CodeActionContext - -makeExtendingDatatype "CodeActionParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [ ("_textDocument", [t|TextDocumentIdentifier|]), - ("_range", [t|Range|]), - ("_context", [t|CodeActionContext|]) + CodeActionKind_QuickFix + , CodeActionKind_Refactor + , CodeActionKind_RefactorExtract + , CodeActionKind_RefactorInline + , CodeActionKind_RefactorRewrite + , CodeActionKind_Source + , CodeActionKind_SourceOrganizeImports + , CodeActionKind_SourceFixAll ] -deriveJSON lspOptions ''CodeActionParams - -newtype Reason = Reason {_reason :: Text} - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''Reason - --- | A code action represents a change that can be performed in code, e.g. to fix a problem or --- to refactor code. --- --- A CodeAction must set either '_edit' and/or a '_command'. If both are supplied, --- the '_edit' is applied first, then the '_command' is executed. -data CodeAction = - CodeAction - { -- | A short, human-readable, title for this code action. - _title :: Text, - -- | The kind of the code action. Used to filter code actions. - _kind :: Maybe CodeActionKind, - -- | The diagnostics that this code action resolves. - _diagnostics :: Maybe (List Diagnostic), - -- | Marks this as a preferred action. Preferred actions are used by the `auto fix` command and can be targeted - -- by keybindings. - -- - -- A quick fix should be marked preferred if it properly addresses the underlying error. - -- A refactoring should be marked preferred if it is the most reasonable choice of actions to take. - -- - -- Since LSP 3.15.0 - _isPreferred :: Maybe Bool, - _disabled :: Maybe Reason, -- ^ Marks that the code action cannot currently be applied. - -- | The workspace edit this code action performs. - _edit :: Maybe WorkspaceEdit, - -- | A command this code action executes. If a code action - -- provides an edit and a command, first the edit is - -- executed and then the command. - _command :: Maybe Command, - -- | A data entry field that is preserved on a code action between - -- a `textDocument/codeAction` and a `codeAction/resolve` request. - -- - -- @since 3.16.0 - _xdata :: Maybe Value - } - deriving (Read, Show, Eq) -deriveJSON lspOptions ''CodeAction diff --git a/lsp-types/src/Language/LSP/Types/CodeLens.hs b/lsp-types/src/Language/LSP/Types/CodeLens.hs deleted file mode 100644 index 86ec9580f..000000000 --- a/lsp-types/src/Language/LSP/Types/CodeLens.hs +++ /dev/null @@ -1,64 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.CodeLens where - -import Data.Aeson -import Data.Aeson.TH -import Language.LSP.Types.Command -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - --- ------------------------------------- - -data CodeLensClientCapabilities = - CodeLensClientCapabilities - { -- | Whether code lens supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CodeLensClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "CodeLensOptions" [''WorkDoneProgressOptions] - [ ("_resolveProvider", [t| Maybe Bool |] )] -deriveJSON lspOptions ''CodeLensOptions - -makeExtendingDatatype "CodeLensRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''CodeLensOptions - ] [] -deriveJSON lspOptions ''CodeLensRegistrationOptions - --- ------------------------------------- - -makeExtendingDatatype "CodeLensParams" - [ ''WorkDoneProgressParams, - ''PartialResultParams - ] - [("_textDocument", [t|TextDocumentIdentifier|])] -deriveJSON lspOptions ''CodeLensParams - --- ------------------------------------- - --- | A code lens represents a command that should be shown along with source --- text, like the number of references, a way to run tests, etc. --- --- A code lens is _unresolved_ when no command is associated to it. For --- performance reasons the creation of a code lens and resolving should be done --- in two stages. -data CodeLens = - CodeLens - { -- | The range in which this code lens is valid. Should only span a single line. - _range :: Range - , -- | The command this code lens represents. - _command :: Maybe Command - , -- | A data entry field that is preserved on a code lens item between - -- a code lens and a code lens resolve request. - _xdata :: Maybe Value - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''CodeLens diff --git a/lsp-types/src/Language/LSP/Types/Command.hs b/lsp-types/src/Language/LSP/Types/Command.hs deleted file mode 100644 index c1c54cd34..000000000 --- a/lsp-types/src/Language/LSP/Types/Command.hs +++ /dev/null @@ -1,51 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.Command where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text -import Language.LSP.Types.Common -import Language.LSP.Types.Progress -import Language.LSP.Types.Utils - --- ------------------------------------- - -data ExecuteCommandClientCapabilities = - ExecuteCommandClientCapabilities - { _dynamicRegistration :: Maybe Bool -- ^Execute command supports dynamic - -- registration. - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ExecuteCommandClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "ExecuteCommandOptions" [''WorkDoneProgressOptions] - [("_commands", [t| List Text |])] -deriveJSON lspOptions ''ExecuteCommandOptions - -makeExtendingDatatype "ExecuteCommandRegistrationOptions" [''ExecuteCommandOptions] [] -deriveJSON lspOptions ''ExecuteCommandRegistrationOptions - --- ------------------------------------- - -makeExtendingDatatype "ExecuteCommandParams" [''WorkDoneProgressParams] - [ ("_command", [t| Text |]) - , ("_arguments", [t| Maybe (List Value) |]) - ] -deriveJSON lspOptions ''ExecuteCommandParams - -data Command = - Command - { -- | Title of the command, like @save@. - _title :: Text - , -- | The identifier of the actual command handler. - _command :: Text - , -- | Arguments that the command handler should be invoked with. - _arguments :: Maybe (List Value) - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''Command - diff --git a/lsp-types/src/Language/LSP/Types/Common.hs b/lsp-types/src/Language/LSP/Types/Common.hs index 36ad58d43..3197097ed 100644 --- a/lsp-types/src/Language/LSP/Types/Common.hs +++ b/lsp-types/src/Language/LSP/Types/Common.hs @@ -1,30 +1,110 @@ -{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE KindSignatures #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} --- | Common types that aren't in the specification +{-| +Common types that aren't in the specification, but which get widely used. +-} module Language.LSP.Types.Common ( type (|?) (..) + , _L + , _R , toEither - , List (..) - , Empty (..) + , MessageDirection (..) + , MessageKind (..) + , SMessageDirection (..) + , SMessageKind (..) + , AString (..) + , AnInteger (..) , Int32 - , UInt ) where - -import Control.Applicative -import Control.DeepSeq -import Data.Aeson -import Data.Hashable -import Data.Int (Int32) -import Data.Mod.Word -import Text.Read (Read(readPrec)) -import GHC.Generics hiding (UInt) -import GHC.TypeNats hiding (Mod) -import Data.Bifunctor (bimap) + , UInt + , Null (..) + , absorbNull + , nullToMaybe + ) where + +import Control.Applicative +import Control.DeepSeq +import Control.Lens +import Data.Aeson hiding (Null) +import qualified Data.Aeson as J +import Data.Hashable +import Data.Int (Int32) +import Data.Mod.Word +import Data.Proxy +import qualified Data.Text as T +import GHC.Generics hiding (UInt) +import GHC.TypeLits hiding (Mod) +import Text.Read (Read (readPrec)) + +-- | Which direction messages are sent in. +data MessageDirection = ServerToClient | ClientToServer +-- | What kind of message is sent. +data MessageKind = Notification | Request + +-- | Singleton type for 'MessageDirection'. +data SMessageDirection (f :: MessageDirection) where + SClientToServer :: SMessageDirection ClientToServer + SServerToClient :: SMessageDirection ServerToClient + SBothDirections :: SMessageDirection f + +-- | Singleton type for 'MessageKind'. +data SMessageKind (f :: MessageKind) where + SNotification :: SMessageKind Notification + SRequest :: SMessageKind Request + SBothTypes :: SMessageKind f + +-- | A type whose only inhabitant is a single, statically-known string. +data AString (s :: Symbol) where + AString :: KnownSymbol s => AString s + +instance Show (AString s) where + show AString = symbolVal (Proxy @s) +instance Eq (AString s) where + _ == _ = True +instance Ord (AString s) where + compare _ _ = EQ + +instance ToJSON (AString s) where + toJSON AString = toJSON (T.pack (symbolVal (Proxy @s))) + +instance KnownSymbol s => FromJSON (AString s) where + parseJSON = withText "string literal type" $ \s -> do + let sym = symbolVal (Proxy @s) + if s == T.pack sym + then pure AString + else fail $ "wrong string, got: " <> show s <> " expected " <> sym + +-- | A type whose only inhabitant is a single, statically-known integer. +data AnInteger (n :: Nat) where + AnInteger :: KnownNat n => AnInteger n + +instance Show (AnInteger n) where + show AnInteger = show $ natVal (Proxy @n) +instance Eq (AnInteger n) where + _ == _ = True +instance Ord (AnInteger n) where + compare _ _ = EQ + +instance ToJSON (AnInteger n) where + toJSON AnInteger = toJSON (natVal (Proxy @n)) + +instance KnownNat n => FromJSON (AnInteger n) where + parseJSON = withScientific "string literal type" $ \n -> do + let nat = natVal (Proxy @n) + if truncate n == nat + then pure AnInteger + else fail $ "wrong string, got: " <> show n <> " expected " <> show nat -- | The "uinteger" type in the LSP spec. -- @@ -55,13 +135,24 @@ instance ToJSON UInt where instance FromJSON UInt where parseJSON v = fromInteger <$> parseJSON v --- | A terser, isomorphic data type for 'Either', that does not get tagged when --- converting to and from JSON. +-- | An untagged union, isomorphic to 'Either'. data a |? b = InL a | InR b deriving (Read,Show,Eq,Ord,Generic) infixr |? +-- | Prism for the left-hand side of an '(|?)'. +_L :: Prism' (a |? b) a +_L = prism' InL $ \case + InL a -> Just a + InR _ -> Nothing + +-- | Prism for the right-hand side of an '(|?)'. +_R :: Prism' (a |? b) b +_R = prism' InR $ \case + InL _ -> Nothing + InR b -> Just b + toEither :: a |? b -> Either a b toEither (InL a) = Left a toEither (InR b) = Right b @@ -78,26 +169,21 @@ instance (FromJSON a, FromJSON b) => FromJSON (a |? b) where instance (NFData a, NFData b) => NFData (a |? b) --- | All LSP types representing a list **must** use this type rather than '[]'. --- In particular this is necessary to change the 'FromJSON' instance to be compatible --- with Elisp (where empty lists show up as 'null') -newtype List a = List [a] - deriving stock (Traversable,Generic) - deriving newtype (Show,Read,Eq,Ord,Semigroup,Monoid,Functor,Foldable) - -instance NFData a => NFData (List a) - -instance (ToJSON a) => ToJSON (List a) where - toJSON (List ls) = toJSON ls - -instance (FromJSON a) => FromJSON (List a) where - parseJSON Null = return (List []) - parseJSON v = List <$> parseJSON v - -data Empty = Empty deriving (Eq,Ord,Show) -instance ToJSON Empty where - toJSON Empty = Null -instance FromJSON Empty where - parseJSON Null = pure Empty - parseJSON (Object o) | o == mempty = pure Empty - parseJSON _ = fail "expected 'null' or '{}'" +-- We could use 'Proxy' for this, as aeson also serializes it to/from null, +-- but this is more explicit. +-- | A type for things that should just literally be null and nothing else. +data Null = Null deriving (Eq,Ord,Show) + +instance ToJSON Null where + toJSON Null = J.Null +instance FromJSON Null where + parseJSON J.Null = pure Null + parseJSON _ = fail "expected 'null'" + +absorbNull :: Monoid a => a |? Null -> a +absorbNull (InL a) = a +absorbNull (InR _) = mempty + +nullToMaybe :: a |? Null -> Maybe a +nullToMaybe (InL a) = Just a +nullToMaybe (InR _) = Nothing diff --git a/lsp-types/src/Language/LSP/Types/Completion.hs b/lsp-types/src/Language/LSP/Types/Completion.hs deleted file mode 100644 index e1f17f168..000000000 --- a/lsp-types/src/Language/LSP/Types/Completion.hs +++ /dev/null @@ -1,418 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.Completion where - -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Scientific ( Scientific ) -import Data.Text ( Text ) -import Language.LSP.Types.Command -import Language.LSP.Types.Common -import Language.LSP.Types.MarkupContent -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils -import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types.Location (Range) - -data CompletionItemKind = CiText - | CiMethod - | CiFunction - | CiConstructor - | CiField - | CiVariable - | CiClass - | CiInterface - | CiModule - | CiProperty - | CiUnit - | CiValue - | CiEnum - | CiKeyword - | CiSnippet - | CiColor - | CiFile - | CiReference - | CiFolder - | CiEnumMember - | CiConstant - | CiStruct - | CiEvent - | CiOperator - | CiTypeParameter - deriving (Read,Show,Eq,Ord) - -instance A.ToJSON CompletionItemKind where - toJSON CiText = A.Number 1 - toJSON CiMethod = A.Number 2 - toJSON CiFunction = A.Number 3 - toJSON CiConstructor = A.Number 4 - toJSON CiField = A.Number 5 - toJSON CiVariable = A.Number 6 - toJSON CiClass = A.Number 7 - toJSON CiInterface = A.Number 8 - toJSON CiModule = A.Number 9 - toJSON CiProperty = A.Number 10 - toJSON CiUnit = A.Number 11 - toJSON CiValue = A.Number 12 - toJSON CiEnum = A.Number 13 - toJSON CiKeyword = A.Number 14 - toJSON CiSnippet = A.Number 15 - toJSON CiColor = A.Number 16 - toJSON CiFile = A.Number 17 - toJSON CiReference = A.Number 18 - toJSON CiFolder = A.Number 19 - toJSON CiEnumMember = A.Number 20 - toJSON CiConstant = A.Number 21 - toJSON CiStruct = A.Number 22 - toJSON CiEvent = A.Number 23 - toJSON CiOperator = A.Number 24 - toJSON CiTypeParameter = A.Number 25 - -instance A.FromJSON CompletionItemKind where - parseJSON (A.Number 1) = pure CiText - parseJSON (A.Number 2) = pure CiMethod - parseJSON (A.Number 3) = pure CiFunction - parseJSON (A.Number 4) = pure CiConstructor - parseJSON (A.Number 5) = pure CiField - parseJSON (A.Number 6) = pure CiVariable - parseJSON (A.Number 7) = pure CiClass - parseJSON (A.Number 8) = pure CiInterface - parseJSON (A.Number 9) = pure CiModule - parseJSON (A.Number 10) = pure CiProperty - parseJSON (A.Number 11) = pure CiUnit - parseJSON (A.Number 12) = pure CiValue - parseJSON (A.Number 13) = pure CiEnum - parseJSON (A.Number 14) = pure CiKeyword - parseJSON (A.Number 15) = pure CiSnippet - parseJSON (A.Number 16) = pure CiColor - parseJSON (A.Number 17) = pure CiFile - parseJSON (A.Number 18) = pure CiReference - parseJSON (A.Number 19) = pure CiFolder - parseJSON (A.Number 20) = pure CiEnumMember - parseJSON (A.Number 21) = pure CiConstant - parseJSON (A.Number 22) = pure CiStruct - parseJSON (A.Number 23) = pure CiEvent - parseJSON (A.Number 24) = pure CiOperator - parseJSON (A.Number 25) = pure CiTypeParameter - parseJSON _ = fail "CompletionItemKind" - -data CompletionItemTag - -- | Render a completion as obsolete, usually using a strike-out. - = CitDeprecated - | CitUnknown Scientific - deriving (Eq, Ord, Show, Read) - -instance A.ToJSON CompletionItemTag where - toJSON CitDeprecated = A.Number 1 - toJSON (CitUnknown i) = A.Number i - -instance A.FromJSON CompletionItemTag where - parseJSON (A.Number 1) = pure CitDeprecated - parseJSON _ = fail "CompletionItemTag" - -data CompletionItemTagsClientCapabilities = - CompletionItemTagsClientCapabilities - { -- | The tag supported by the client. - _valueSet :: List CompletionItemTag - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionItemTagsClientCapabilities - -data CompletionItemResolveClientCapabilities = - CompletionItemResolveClientCapabilities - { -- | The properties that a client can resolve lazily. - _properties :: List Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionItemResolveClientCapabilities - -{-| -How whitespace and indentation is handled during completion -item insertion. - -@since 3.16.0 --} -data InsertTextMode = - -- | The insertion or replace strings is taken as it is. If the - -- value is multi line the lines below the cursor will be - -- inserted using the indentation defined in the string value. - -- The client will not apply any kind of adjustments to the - -- string. - AsIs - -- | The editor adjusts leading whitespace of new lines so that - -- they match the indentation up to the cursor of the line for - -- which the item is accepted. - -- - -- Consider a line like this: <2tabs><3tabs>foo. Accepting a - -- multi line completion item is indented using 2 tabs and all - -- following lines inserted will be indented using 2 tabs as well. - | AdjustIndentation - deriving (Read,Show,Eq) - -instance A.ToJSON InsertTextMode where - toJSON AsIs = A.Number 1 - toJSON AdjustIndentation = A.Number 2 - -instance A.FromJSON InsertTextMode where - parseJSON (A.Number 1) = pure AsIs - parseJSON (A.Number 2) = pure AdjustIndentation - parseJSON _ = fail "InsertTextMode" - -data CompletionItemInsertTextModeClientCapabilities = - CompletionItemInsertTextModeClientCapabilities - { _valueSet :: List InsertTextMode - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionItemInsertTextModeClientCapabilities - -data CompletionItemClientCapabilities = - CompletionItemClientCapabilities - { -- | Client supports snippets as insert text. - -- - -- A snippet can define tab stops and placeholders with `$1`, `$2` and - -- `${3:foo}`. `$0` defines the final tab stop, it defaults to the end of - -- the snippet. Placeholders with equal identifiers are linked, that is - -- typing in one will update others too. - _snippetSupport :: Maybe Bool - - -- | Client supports commit characters on a completion item. - , _commitCharactersSupport :: Maybe Bool - - -- | Client supports the follow content formats for the documentation - -- property. The order describes the preferred format of the client. - , _documentationFormat :: Maybe (List MarkupKind) - - -- | Client supports the deprecated property on a completion item. - , _deprecatedSupport :: Maybe Bool - - -- | Client supports the preselect property on a completion item. - , _preselectSupport :: Maybe Bool - - -- | Client supports the tag property on a completion item. Clients - -- supporting tags have to handle unknown tags gracefully. Clients - -- especially need to preserve unknown tags when sending a - -- completion item back to the server in a resolve call. - -- - -- @since 3.15.0 - , _tagSupport :: Maybe CompletionItemTagsClientCapabilities - -- | Client supports insert replace edit to control different behavior if - -- completion item is inserted in the text or should replace text. - -- - -- @since 3.16.0 - , _insertReplaceSupport :: Maybe Bool - -- | Indicates which properties a client can resolve lazily on a - -- completion item. Before version 3.16.0 only the predefined properties - -- `documentation` and `details` could be resolved lazily. - -- - -- @since 3.16.0 - , _resolveSupport :: Maybe CompletionItemResolveClientCapabilities - -- | The client supports the `insertTextMode` property on - -- a completion item to override the whitespace handling mode - -- as defined by the client (see `insertTextMode`). - -- - -- @since 3.16.0 - , _insertTextModeSupport :: Maybe CompletionItemInsertTextModeClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionItemClientCapabilities - -data CompletionItemKindClientCapabilities = - CompletionItemKindClientCapabilities - { -- | The completion item kind values the client supports. When this - -- property exists the client also guarantees that it will - -- handle values outside its set gracefully and falls back - -- to a default value when unknown. - _valueSet :: Maybe (List CompletionItemKind) - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionItemKindClientCapabilities - -data CompletionClientCapabilities = - CompletionClientCapabilities - { _dynamicRegistration :: Maybe Bool -- ^ Whether completion supports dynamic - -- registration. - , _completionItem :: Maybe CompletionItemClientCapabilities - , _completionItemKind :: Maybe CompletionItemKindClientCapabilities - , _contextSupport :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CompletionClientCapabilities - --- ------------------------------------- - -data InsertTextFormat - = PlainText -- ^The primary text to be inserted is treated as a plain string. - | Snippet - -- ^ The primary text to be inserted is treated as a snippet. - -- - -- A snippet can define tab stops and placeholders with `$1`, `$2` - -- and `${3:foo}`. `$0` defines the final tab stop, it defaults to - -- the end of the snippet. Placeholders with equal identifiers are linked, - -- that is typing in one will update others too. - -- - -- See also: https://github.com/Microsoft/vscode/blob/master/src/vs/editor/contrib/snippet/common/snippet.md - deriving (Show, Read, Eq) - -instance A.ToJSON InsertTextFormat where - toJSON PlainText = A.Number 1 - toJSON Snippet = A.Number 2 - -instance A.FromJSON InsertTextFormat where - parseJSON (A.Number 1) = pure PlainText - parseJSON (A.Number 2) = pure Snippet - parseJSON _ = fail "InsertTextFormat" - -data CompletionDoc = CompletionDocString Text - | CompletionDocMarkup MarkupContent - deriving (Show, Read, Eq) - -deriveJSON lspOptionsUntagged ''CompletionDoc - -data InsertReplaceEdit = - InsertReplaceEdit - { _newText :: Text -- ^ The string to be inserted. - , _insert :: Range -- ^ The range if the insert is requested - , _repalce :: Range -- ^ The range if the replace is requested. - } - deriving (Read,Show,Eq) -deriveJSON lspOptions ''InsertReplaceEdit - -data CompletionEdit = CompletionEditText TextEdit | CompletionEditInsertReplace InsertReplaceEdit - deriving (Read,Show,Eq) - -deriveJSON lspOptionsUntagged ''CompletionEdit - -data CompletionItem = - CompletionItem - { _label :: Text -- ^ The label of this completion item. By default also - -- the text that is inserted when selecting this - -- completion. - , _kind :: Maybe CompletionItemKind - , _tags :: Maybe (List CompletionItemTag) -- ^ Tags for this completion item. - , _detail :: Maybe Text -- ^ A human-readable string with additional - -- information about this item, like type or - -- symbol information. - , _documentation :: Maybe CompletionDoc -- ^ A human-readable string that represents - -- a doc-comment. - , _deprecated :: Maybe Bool -- ^ Indicates if this item is deprecated. - , _preselect :: Maybe Bool - -- ^ Select this item when showing. - -- *Note* that only one completion item can be selected and that the - -- tool / client decides which item that is. The rule is that the *first* - -- item of those that match best is selected. - , _sortText :: Maybe Text -- ^ A string that should be used when filtering - -- a set of completion items. When `falsy` the - -- label is used. - , _filterText :: Maybe Text -- ^ A string that should be used when - -- filtering a set of completion items. When - -- `falsy` the label is used. - , _insertText :: Maybe Text -- ^ A string that should be inserted a - -- document when selecting this completion. - -- When `falsy` the label is used. - , _insertTextFormat :: Maybe InsertTextFormat - -- ^ The format of the insert text. The format applies to both the - -- `insertText` property and the `newText` property of a provided - -- `textEdit`. - , _insertTextMode :: Maybe InsertTextMode - -- ^ How whitespace and indentation is handled during completion - -- item insertion. If not provided the client's default value depends on - -- the @textDocument.completion.insertTextMode@ client capability. - , _textEdit :: Maybe CompletionEdit - -- ^ An edit which is applied to a document when selecting this - -- completion. When an edit is provided the value of `insertText` is - -- ignored. - -- - -- *Note:* The range of the edit must be a single line range and it - -- must contain the position at which completion has been requested. - , _additionalTextEdits :: Maybe (List TextEdit) - -- ^ An optional array of additional text edits that are applied when - -- selecting this completion. Edits must not overlap with the main edit - -- nor with themselves. - , _commitCharacters :: Maybe (List Text) - -- ^ An optional set of characters that when pressed while this completion - -- is active will accept it first and then type that character. *Note* - -- that all commit characters should have `length=1` and that superfluous - -- characters will be ignored. - , _command :: Maybe Command - -- ^ An optional command that is executed *after* inserting this - -- completion. *Note* that additional modifications to the current - -- document should be described with the additionalTextEdits-property. - , _xdata :: Maybe A.Value -- ^ An data entry field that is preserved on a - -- completion item between a completion and a - -- completion resolve request. - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''CompletionItem - --- | Represents a collection of 'CompletionItem's to be presented in the editor. -data CompletionList = - CompletionList - { _isIncomplete :: Bool -- ^ This list it not complete. Further typing - -- should result in recomputing this list. - , _items :: List CompletionItem -- ^ The completion items. - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''CompletionList - --- | How a completion was triggered -data CompletionTriggerKind = -- | Completion was triggered by typing an identifier (24x7 code - -- complete), manual invocation (e.g Ctrl+Space) or via API. - CtInvoked - -- | Completion was triggered by a trigger character specified by - -- the `triggerCharacters` properties of the `CompletionRegistrationOptions`. - | CtTriggerCharacter - -- | Completion was re-triggered as the current completion list is incomplete. - | CtTriggerForIncompleteCompletions - -- | An unknown 'CompletionTriggerKind' not yet supported in haskell-lsp. - | CtUnknown Scientific - deriving (Read, Show, Eq) - -instance A.ToJSON CompletionTriggerKind where - toJSON CtInvoked = A.Number 1 - toJSON CtTriggerCharacter = A.Number 2 - toJSON CtTriggerForIncompleteCompletions = A.Number 3 - toJSON (CtUnknown x) = A.Number x - -instance A.FromJSON CompletionTriggerKind where - parseJSON (A.Number 1) = pure CtInvoked - parseJSON (A.Number 2) = pure CtTriggerCharacter - parseJSON (A.Number 3) = pure CtTriggerForIncompleteCompletions - parseJSON (A.Number x) = pure (CtUnknown x) - parseJSON _ = fail "CompletionTriggerKind" - -makeExtendingDatatype "CompletionOptions" [''WorkDoneProgressOptions] - [ ("_triggerCharacters", [t| Maybe [Text] |]) - , ("_allCommitCharacters", [t| Maybe [Text] |]) - , ("_resolveProvider", [t| Maybe Bool|]) - ] -deriveJSON lspOptions ''CompletionOptions - -makeExtendingDatatype "CompletionRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''CompletionOptions - ] - [] -deriveJSON lspOptions ''CompletionRegistrationOptions - -data CompletionContext = - CompletionContext - { _triggerKind :: CompletionTriggerKind -- ^ How the completion was triggered. - , _triggerCharacter :: Maybe Text - -- ^ The trigger character (a single character) that has trigger code complete. - -- Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''CompletionContext - -makeExtendingDatatype "CompletionParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] - [ ("_context", [t| Maybe CompletionContext |]) ] -deriveJSON lspOptions ''CompletionParams - diff --git a/lsp-types/src/Language/LSP/Types/Configuration.hs b/lsp-types/src/Language/LSP/Types/Configuration.hs deleted file mode 100644 index a33860dbd..000000000 --- a/lsp-types/src/Language/LSP/Types/Configuration.hs +++ /dev/null @@ -1,42 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.Configuration where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.Utils - --- ------------------------------------- - -data DidChangeConfigurationClientCapabilities = - DidChangeConfigurationClientCapabilities - { _dynamicRegistration :: Maybe Bool -- ^Did change configuration - -- notification supports dynamic - -- registration. - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DidChangeConfigurationClientCapabilities - -data DidChangeConfigurationParams = - DidChangeConfigurationParams - { _settings :: Value -- ^ The actual changed settings - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DidChangeConfigurationParams - --- --------------------------------------------------------------------- - -data ConfigurationItem = - ConfigurationItem - { _scopeUri :: Maybe Text -- ^ The scope to get the configuration section for. - , _section :: Maybe Text -- ^ The configuration section asked for. - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ConfigurationItem - -data ConfigurationParams = - ConfigurationParams - { _items :: List ConfigurationItem - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''ConfigurationParams diff --git a/lsp-types/src/Language/LSP/Types/Declaration.hs b/lsp-types/src/Language/LSP/Types/Declaration.hs deleted file mode 100644 index 00ba8747e..000000000 --- a/lsp-types/src/Language/LSP/Types/Declaration.hs +++ /dev/null @@ -1,39 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.Declaration where - -import Data.Aeson.TH -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data DeclarationClientCapabilities = - DeclarationClientCapabilities - { -- | Whether declaration supports dynamic registration. If this is set to 'true' - -- the client supports the new 'DeclarationRegistrationOptions' return value - -- for the corresponding server capability as well. - _dynamicRegistration :: Maybe Bool - -- | The client supports additional metadata in the form of declaration links. - , _linkSupport :: Maybe Bool - } - deriving (Read, Show, Eq) -deriveJSON lspOptions ''DeclarationClientCapabilities - -makeExtendingDatatype "DeclarationOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DeclarationOptions - -makeExtendingDatatype "DeclarationRegistrationOptions" - [ ''DeclarationOptions - , ''TextDocumentRegistrationOptions - , ''StaticRegistrationOptions - ] [] -deriveJSON lspOptions ''DeclarationRegistrationOptions - -makeExtendingDatatype "DeclarationParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] [] -deriveJSON lspOptions ''DeclarationParams diff --git a/lsp-types/src/Language/LSP/Types/Definition.hs b/lsp-types/src/Language/LSP/Types/Definition.hs deleted file mode 100644 index 1e308680c..000000000 --- a/lsp-types/src/Language/LSP/Types/Definition.hs +++ /dev/null @@ -1,36 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.Definition where - -import Data.Aeson.TH -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data DefinitionClientCapabilities = - DefinitionClientCapabilities - { -- | Whether definition supports dynamic registration. - _dynamicRegistration :: Maybe Bool - -- | The client supports additional metadata in the form of definition - -- links. - -- Since LSP 3.14.0 - , _linkSupport :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''DefinitionClientCapabilities - -makeExtendingDatatype "DefinitionOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DefinitionOptions - -makeExtendingDatatype "DefinitionRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DefinitionOptions - ] [] -deriveJSON lspOptions ''DefinitionRegistrationOptions - -makeExtendingDatatype "DefinitionParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] [] -deriveJSON lspOptions ''DefinitionParams diff --git a/lsp-types/src/Language/LSP/Types/Diagnostic.hs b/lsp-types/src/Language/LSP/Types/Diagnostic.hs deleted file mode 100644 index 4d17b1ba9..000000000 --- a/lsp-types/src/Language/LSP/Types/Diagnostic.hs +++ /dev/null @@ -1,139 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE TypeOperators #-} - -module Language.LSP.Types.Diagnostic where - -import Control.DeepSeq -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Text -import GHC.Generics hiding (UInt) -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils - --- --------------------------------------------------------------------- - -data DiagnosticSeverity - = DsError -- ^ Error = 1, - | DsWarning -- ^ Warning = 2, - | DsInfo -- ^ Info = 3, - | DsHint -- ^ Hint = 4 - deriving (Eq,Ord,Show,Read, Generic) - -instance NFData DiagnosticSeverity - -instance A.ToJSON DiagnosticSeverity where - toJSON DsError = A.Number 1 - toJSON DsWarning = A.Number 2 - toJSON DsInfo = A.Number 3 - toJSON DsHint = A.Number 4 - -instance A.FromJSON DiagnosticSeverity where - parseJSON (A.Number 1) = pure DsError - parseJSON (A.Number 2) = pure DsWarning - parseJSON (A.Number 3) = pure DsInfo - parseJSON (A.Number 4) = pure DsHint - parseJSON _ = fail "DiagnosticSeverity" - -data DiagnosticTag - -- | Unused or unnecessary code. - -- - -- Clients are allowed to render diagnostics with this tag faded out - -- instead of having an error squiggle. - = DtUnnecessary - -- | Deprecated or obsolete code. - -- - -- Clients are allowed to rendered diagnostics with this tag strike - -- through. - | DtDeprecated - deriving (Eq, Ord, Show, Read, Generic) - -instance NFData DiagnosticTag - -instance A.ToJSON DiagnosticTag where - toJSON DtUnnecessary = A.Number 1 - toJSON DtDeprecated = A.Number 2 - -instance A.FromJSON DiagnosticTag where - parseJSON (A.Number 1) = pure DtUnnecessary - parseJSON (A.Number 2) = pure DtDeprecated - parseJSON _ = fail "DiagnosticTag" - --- --------------------------------------------------------------------- - -data DiagnosticRelatedInformation = - DiagnosticRelatedInformation - { _location :: Location - , _message :: Text - } deriving (Show, Read, Eq, Ord, Generic) - -instance NFData DiagnosticRelatedInformation - -deriveJSON lspOptions ''DiagnosticRelatedInformation - --- --------------------------------------------------------------------- - -type DiagnosticSource = Text -data Diagnostic = - Diagnostic - { _range :: Range - , _severity :: Maybe DiagnosticSeverity - , _code :: Maybe (Int32 |? Text) - , _source :: Maybe DiagnosticSource - , _message :: Text - , _tags :: Maybe (List DiagnosticTag) - , _relatedInformation :: Maybe (List DiagnosticRelatedInformation) - } deriving (Show, Read, Eq, Ord, Generic) - -instance NFData Diagnostic - -deriveJSON lspOptions ''Diagnostic - --- ------------------------------------- - -data PublishDiagnosticsTagsClientCapabilities = - PublishDiagnosticsTagsClientCapabilities - { -- | The tags supported by the client. - _valueSet :: List DiagnosticTag - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''PublishDiagnosticsTagsClientCapabilities - -data PublishDiagnosticsClientCapabilities = - PublishDiagnosticsClientCapabilities - { -- | Whether the clients accepts diagnostics with related information. - _relatedInformation :: Maybe Bool - -- | Client supports the tag property to provide metadata about a - -- diagnostic. - -- - -- Clients supporting tags have to handle unknown tags gracefully. - -- - -- Since LSP 3.15.0 - , _tagSupport :: Maybe PublishDiagnosticsTagsClientCapabilities - -- | Whether the client interprets the version property of the - -- @textDocument/publishDiagnostics@ notification's parameter. - -- - -- Since LSP 3.15.0 - , _versionSupport :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''PublishDiagnosticsClientCapabilities - -data PublishDiagnosticsParams = - PublishDiagnosticsParams - { -- | The URI for which diagnostic information is reported. - _uri :: Uri - -- | Optional the version number of the document the diagnostics are - -- published for. - -- - -- Since LSP 3.15.0 - , _version :: Maybe UInt - -- | An array of diagnostic information items. - , _diagnostics :: List Diagnostic - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''PublishDiagnosticsParams diff --git a/lsp-types/src/Language/LSP/Types/DocumentColor.hs b/lsp-types/src/Language/LSP/Types/DocumentColor.hs deleted file mode 100644 index 50b0fa7f3..000000000 --- a/lsp-types/src/Language/LSP/Types/DocumentColor.hs +++ /dev/null @@ -1,91 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} -module Language.LSP.Types.DocumentColor where - -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils -import Language.LSP.Types.WorkspaceEdit - -data DocumentColorClientCapabilities = - DocumentColorClientCapabilities - { -- | Whether document color supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''DocumentColorClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "DocumentColorOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DocumentColorOptions - -makeExtendingDatatype "DocumentColorRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''StaticRegistrationOptions - , ''DocumentColorOptions - ] [] -deriveJSON lspOptions ''DocumentColorRegistrationOptions - --- ------------------------------------- - -makeExtendingDatatype "DocumentColorParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_textDocument", [t| TextDocumentIdentifier |])] -deriveJSON lspOptions ''DocumentColorParams - --- ------------------------------------- - --- | Represents a color in RGBA space. -data Color = - Color - { _red :: Float -- ^ The red component of this color in the range [0-1]. - , _green :: Float -- ^ The green component of this color in the range [0-1]. - , _blue :: Float -- ^ The blue component of this color in the range [0-1]. - , _alpha :: Float -- ^ The alpha component of this color in the range [0-1]. - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''Color - -data ColorInformation = - ColorInformation - { _range :: Range -- ^ The range in the document where this color appears. - , _color :: Color -- ^ The actual color value for this color range. - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''ColorInformation - --- ------------------------------------- - -makeExtendingDatatype "ColorPresentationParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [ ("_textDocument", [t| TextDocumentIdentifier |]) - , ("_color", [t| Color |]) - , ("_range", [t| Range |]) - ] -deriveJSON lspOptions ''ColorPresentationParams - --- ------------------------------------- - -data ColorPresentation = - ColorPresentation - { -- | The label of this color presentation. It will be shown on the color - -- picker header. By default this is also the text that is inserted when selecting - -- this color presentation. - _label :: Text - -- | A 'TextEdit' which is applied to a document when selecting - -- this presentation for the color. When `falsy` the '_label' - -- is used. - , _textEdit :: Maybe TextEdit - -- | An optional array of additional 'TextEdit's that are applied when - -- selecting this color presentation. Edits must not overlap with the main - -- '_textEdit' nor with themselves. - , _additionalTextEdits :: Maybe (List TextEdit) - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''ColorPresentation diff --git a/lsp-types/src/Language/LSP/Types/DocumentFilter.hs b/lsp-types/src/Language/LSP/Types/DocumentFilter.hs deleted file mode 100644 index 49ac85924..000000000 --- a/lsp-types/src/Language/LSP/Types/DocumentFilter.hs +++ /dev/null @@ -1,36 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.DocumentFilter where - -import Data.Aeson.TH -import Data.Text ( Text ) -import Language.LSP.Types.Common -import Language.LSP.Types.Utils - --- --------------------------------------------------------------------- - -data DocumentFilter = - DocumentFilter - { -- | A language id, like `typescript`. - _language :: Maybe Text - -- | A Uri scheme, like @file@ or @untitled@. - , _scheme :: Maybe Text - , -- | A glob pattern, like `*.{ts,js}`. - -- - -- Glob patterns can have the following syntax: - -- - @*@ to match one or more characters in a path segment - -- - @?@ to match on one character in a path segment - -- - @**@ to match any number of path segments, including none - -- - @{}@ to group conditions (e.g. @**​/*.{ts,js}@ matches all TypeScript and JavaScript files) - -- - @[]@ to declare a range of characters to match in a path segment (e.g., @example.[0-9]@ to match on @example.0@, @example.1@, …) - -- - @[!...]@ to negate a range of characters to match in a path segment (e.g., @example.[!0-9]@ to match on @example.a@, @example.b@, but not @example.0@) - _pattern :: Maybe Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DocumentFilter - -{- -A document selector is the combination of one or many document filters. - -export type DocumentSelector = DocumentFilter[]; --} -type DocumentSelector = List DocumentFilter diff --git a/lsp-types/src/Language/LSP/Types/DocumentHighlight.hs b/lsp-types/src/Language/LSP/Types/DocumentHighlight.hs deleted file mode 100644 index a6dce6556..000000000 --- a/lsp-types/src/Language/LSP/Types/DocumentHighlight.hs +++ /dev/null @@ -1,71 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.DocumentHighlight where - -import Data.Aeson -import Data.Aeson.TH -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - --- ------------------------------------- - -data DocumentHighlightClientCapabilities = - DocumentHighlightClientCapabilities - { -- | Whether document highlight supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DocumentHighlightClientCapabilities - -makeExtendingDatatype "DocumentHighlightOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DocumentHighlightOptions - -makeExtendingDatatype "DocumentHighlightRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DocumentHighlightOptions - ] [] -deriveJSON lspOptions ''DocumentHighlightRegistrationOptions - -makeExtendingDatatype "DocumentHighlightParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] [] -deriveJSON lspOptions ''DocumentHighlightParams - -data DocumentHighlightKind - = -- | A textual occurrence. - HkText - | -- | Read-access of a symbol, like reading a variable. - HkRead - | -- | Write-access of a symbol, like writing to a variable. - HkWrite - deriving (Read, Show, Eq) - -instance ToJSON DocumentHighlightKind where - toJSON HkText = Number 1 - toJSON HkRead = Number 2 - toJSON HkWrite = Number 3 - -instance FromJSON DocumentHighlightKind where - parseJSON (Number 1) = pure HkText - parseJSON (Number 2) = pure HkRead - parseJSON (Number 3) = pure HkWrite - parseJSON _ = mempty "DocumentHighlightKind" - --- ------------------------------------- - --- | A document highlight is a range inside a text document which deserves --- special attention. Usually a document highlight is visualized by changing the --- background color of its range. -data DocumentHighlight = - DocumentHighlight - { -- | The range this highlight applies to. - _range :: Range - -- | The highlight kind, default is 'HkText'. - , _kind :: Maybe DocumentHighlightKind - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''DocumentHighlight diff --git a/lsp-types/src/Language/LSP/Types/DocumentLink.hs b/lsp-types/src/Language/LSP/Types/DocumentLink.hs deleted file mode 100644 index 494ade1e7..000000000 --- a/lsp-types/src/Language/LSP/Types/DocumentLink.hs +++ /dev/null @@ -1,71 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.DocumentLink where - -import Data.Aeson -import Data.Aeson.TH -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils -import Data.Text (Text) - -data DocumentLinkClientCapabilities = - DocumentLinkClientCapabilities - { -- | Whether document link supports dynamic registration. - _dynamicRegistration :: Maybe Bool - -- | Whether the client supports the `tooltip` property on `DocumentLink`. - -- - -- Since LSP 3.15.0 - , _tooltipSupport :: Maybe Bool - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''DocumentLinkClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "DocumentLinkOptions" [''WorkDoneProgressOptions] - [("_resolveProvider", [t| Maybe Bool |])] -deriveJSON lspOptions ''DocumentLinkOptions - -makeExtendingDatatype "DocumentLinkRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DocumentLinkOptions - ] [] -deriveJSON lspOptions ''DocumentLinkRegistrationOptions - --- ------------------------------------- - -makeExtendingDatatype "DocumentLinkParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_textDocument", [t| TextDocumentIdentifier |])] -deriveJSON lspOptions ''DocumentLinkParams - --- ------------------------------------- - --- | A document link is a range in a text document that links to an internal or --- external resource, like another text document or a web site. -data DocumentLink = - DocumentLink - { -- | The range this link applies to. - _range :: Range - -- | The uri this link points to. If missing a resolve request is sent - -- later. - , _target :: Maybe Uri - -- | The tooltip text when you hover over this link. - -- - -- If a tooltip is provided, is will be displayed in a string that includes - -- instructions on how to trigger the link, such as @{0} (ctrl + click)@. - -- The specific instructions vary depending on OS, user settings, and - -- localization. - -- - -- Since LSP 3.15.0 - , _tooltip :: Maybe Text - -- | A data entry field that is preserved on a document link between a - -- DocumentLinkRequest and a DocumentLinkResolveRequest. - , _xdata :: Maybe Value - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''DocumentLink diff --git a/lsp-types/src/Language/LSP/Types/DocumentSymbol.hs b/lsp-types/src/Language/LSP/Types/DocumentSymbol.hs deleted file mode 100644 index 81a9866e1..000000000 --- a/lsp-types/src/Language/LSP/Types/DocumentSymbol.hs +++ /dev/null @@ -1,253 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} -module Language.LSP.Types.DocumentSymbol where - -import Data.Aeson -import Data.Aeson.TH -import Data.Scientific -import Data.Text (Text) - -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.Utils - --- --------------------------------------------------------------------- - -makeExtendingDatatype "DocumentSymbolOptions" - [''WorkDoneProgressOptions] - [ ("_label", [t| Maybe Bool |])] -deriveJSON lspOptions ''DocumentSymbolOptions - -makeExtendingDatatype "DocumentSymbolRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DocumentSymbolOptions - ] [] -deriveJSON lspOptions ''DocumentSymbolRegistrationOptions - --- --------------------------------------------------------------------- - -makeExtendingDatatype "DocumentSymbolParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [ ("_textDocument", [t| TextDocumentIdentifier |])] -deriveJSON lspOptions ''DocumentSymbolParams - --- ------------------------------------- - -data SymbolKind - = SkFile - | SkModule - | SkNamespace - | SkPackage - | SkClass - | SkMethod - | SkProperty - | SkField - | SkConstructor - | SkEnum - | SkInterface - | SkFunction - | SkVariable - | SkConstant - | SkString - | SkNumber - | SkBoolean - | SkArray - | SkObject - | SkKey - | SkNull - | SkEnumMember - | SkStruct - | SkEvent - | SkOperator - | SkTypeParameter - | SkUnknown Scientific - deriving (Read,Show,Eq, Ord) - -instance ToJSON SymbolKind where - toJSON SkFile = Number 1 - toJSON SkModule = Number 2 - toJSON SkNamespace = Number 3 - toJSON SkPackage = Number 4 - toJSON SkClass = Number 5 - toJSON SkMethod = Number 6 - toJSON SkProperty = Number 7 - toJSON SkField = Number 8 - toJSON SkConstructor = Number 9 - toJSON SkEnum = Number 10 - toJSON SkInterface = Number 11 - toJSON SkFunction = Number 12 - toJSON SkVariable = Number 13 - toJSON SkConstant = Number 14 - toJSON SkString = Number 15 - toJSON SkNumber = Number 16 - toJSON SkBoolean = Number 17 - toJSON SkArray = Number 18 - toJSON SkObject = Number 19 - toJSON SkKey = Number 20 - toJSON SkNull = Number 21 - toJSON SkEnumMember = Number 22 - toJSON SkStruct = Number 23 - toJSON SkEvent = Number 24 - toJSON SkOperator = Number 25 - toJSON SkTypeParameter = Number 26 - toJSON (SkUnknown x) = Number x - -instance FromJSON SymbolKind where - parseJSON (Number 1) = pure SkFile - parseJSON (Number 2) = pure SkModule - parseJSON (Number 3) = pure SkNamespace - parseJSON (Number 4) = pure SkPackage - parseJSON (Number 5) = pure SkClass - parseJSON (Number 6) = pure SkMethod - parseJSON (Number 7) = pure SkProperty - parseJSON (Number 8) = pure SkField - parseJSON (Number 9) = pure SkConstructor - parseJSON (Number 10) = pure SkEnum - parseJSON (Number 11) = pure SkInterface - parseJSON (Number 12) = pure SkFunction - parseJSON (Number 13) = pure SkVariable - parseJSON (Number 14) = pure SkConstant - parseJSON (Number 15) = pure SkString - parseJSON (Number 16) = pure SkNumber - parseJSON (Number 17) = pure SkBoolean - parseJSON (Number 18) = pure SkArray - parseJSON (Number 19) = pure SkObject - parseJSON (Number 20) = pure SkKey - parseJSON (Number 21) = pure SkNull - parseJSON (Number 22) = pure SkEnumMember - parseJSON (Number 23) = pure SkStruct - parseJSON (Number 24) = pure SkEvent - parseJSON (Number 25) = pure SkOperator - parseJSON (Number 26) = pure SkTypeParameter - parseJSON (Number x) = pure (SkUnknown x) - parseJSON _ = fail "SymbolKind" - -{-| -Symbol tags are extra annotations that tweak the rendering of a symbol. - -@since 3.16.0 --} -data SymbolTag = - StDeprecated -- ^ Render a symbol as obsolete, usually using a strike-out. - | StUnknown Scientific - deriving (Read, Show, Eq, Ord) - -instance ToJSON SymbolTag where - toJSON StDeprecated = Number 1 - toJSON (StUnknown x) = Number x - -instance FromJSON SymbolTag where - parseJSON (Number 1) = pure StDeprecated - parseJSON (Number x) = pure (StUnknown x) - parseJSON _ = fail "SymbolTag" - --- ------------------------------------- - -data DocumentSymbolKindClientCapabilities = - DocumentSymbolKindClientCapabilities - { -- | The symbol kind values the client supports. When this - -- property exists the client also guarantees that it will - -- handle values outside its set gracefully and falls back - -- to a default value when unknown. - -- - -- If this property is not present the client only supports - -- the symbol kinds from `File` to `Array` as defined in - -- the initial version of the protocol. - _valueSet :: Maybe (List SymbolKind) - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DocumentSymbolKindClientCapabilities - -data DocumentSymbolTagClientCapabilities = - DocumentSymbolTagClientCapabilities - { -- | The tags supported by the client. - _valueSet :: Maybe (List SymbolTag) - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DocumentSymbolTagClientCapabilities - -data DocumentSymbolClientCapabilities = - DocumentSymbolClientCapabilities - { -- | Whether document symbol supports dynamic registration. - _dynamicRegistration :: Maybe Bool - -- | Specific capabilities for the `SymbolKind`. - , _symbolKind :: Maybe DocumentSymbolKindClientCapabilities - , _hierarchicalDocumentSymbolSupport :: Maybe Bool - -- | The client supports tags on `SymbolInformation`. - -- Clients supporting tags have to handle unknown tags gracefully. - -- - -- @since 3.16.0 - , _tagSupport :: Maybe DocumentSymbolTagClientCapabilities - -- | The client supports an additional label presented in the UI when - -- registering a document symbol provider. - -- - -- @since 3.16.0 - , _labelSupport :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DocumentSymbolClientCapabilities - --- --------------------------------------------------------------------- - --- | Represents programming constructs like variables, classes, interfaces etc. --- that appear in a document. Document symbols can be hierarchical and they --- have two ranges: one that encloses its definition and one that points to its --- most interesting range, e.g. the range of an identifier. -data DocumentSymbol = - DocumentSymbol - { _name :: Text -- ^ The name of this symbol. - -- | More detail for this symbol, e.g the signature of a function. If not - -- provided the name is used. - , _detail :: Maybe Text - , _kind :: SymbolKind -- ^ The kind of this symbol. - , _tags :: Maybe (List SymbolTag) -- ^ Tags for this document symbol. - , _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead. - -- | The range enclosing this symbol not including leading/trailing - -- whitespace but everything else like comments. This information is - -- typically used to determine if the the clients cursor is inside the symbol - -- to reveal in the symbol in the UI. - , _range :: Range - -- | The range that should be selected and revealed when this symbol is being - -- picked, e.g the name of a function. Must be contained by the the '_range'. - , _selectionRange :: Range - -- | Children of this symbol, e.g. properties of a class. - , _children :: Maybe (List DocumentSymbol) - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''DocumentSymbol - --- --------------------------------------------------------------------- - --- | Represents information about programming constructs like variables, classes, --- interfaces etc. -data SymbolInformation = - SymbolInformation - { _name :: Text -- ^ The name of this symbol. - , _kind :: SymbolKind -- ^ The kind of this symbol. - , _tags :: Maybe (List SymbolTag) -- ^ Tags for this symbol. - , _deprecated :: Maybe Bool -- ^ Indicates if this symbol is deprecated. Deprecated, use tags instead. - -- | The location of this symbol. The location's range is used by a tool - -- to reveal the location in the editor. If the symbol is selected in the - -- tool the range's start information is used to position the cursor. So - -- the range usually spans more then the actual symbol's name and does - -- normally include things like visibility modifiers. - -- - -- The range doesn't have to denote a node range in the sense of a abstract - -- syntax tree. It can therefore not be used to re-construct a hierarchy of - -- the symbols. - , _location :: Location - -- | The name of the symbol containing this symbol. This information is for - -- user interface purposes (e.g. to render a qualifier in the user interface - -- if necessary). It can't be used to re-infer a hierarchy for the document - -- symbols. - , _containerName :: Maybe Text - } deriving (Read,Show,Eq) -{-# DEPRECATED _deprecated "Use tags instead" #-} - -deriveJSON lspOptions ''SymbolInformation diff --git a/lsp-types/src/Language/LSP/Types/FoldingRange.hs b/lsp-types/src/Language/LSP/Types/FoldingRange.hs deleted file mode 100644 index c89a4d010..000000000 --- a/lsp-types/src/Language/LSP/Types/FoldingRange.hs +++ /dev/null @@ -1,100 +0,0 @@ -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.FoldingRange where - -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - - --- ------------------------------------- - -data FoldingRangeClientCapabilities = - FoldingRangeClientCapabilities - { -- | Whether implementation supports dynamic registration for folding range - -- providers. If this is set to `true` the client supports the new - -- `(FoldingRangeProviderOptions & TextDocumentRegistrationOptions & StaticRegistrationOptions)` - -- return value for the corresponding server capability as well. - _dynamicRegistration :: Maybe Bool - -- | The maximum number of folding ranges that the client prefers to receive - -- per document. The value serves as a hint, servers are free to follow the limit. - , _rangeLimit :: Maybe UInt - -- | If set, the client signals that it only supports folding complete lines. If set, - -- client will ignore specified `startCharacter` and `endCharacter` properties in a - -- FoldingRange. - , _lineFoldingOnly :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''FoldingRangeClientCapabilities - -makeExtendingDatatype "FoldingRangeOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''FoldingRangeOptions - -makeExtendingDatatype "FoldingRangeRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''FoldingRangeOptions - , ''StaticRegistrationOptions - ] [] -deriveJSON lspOptions ''FoldingRangeRegistrationOptions - - -makeExtendingDatatype "FoldingRangeParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_textDocument", [t| TextDocumentIdentifier |])] -deriveJSON lspOptions ''FoldingRangeParams - --- | Enum of known range kinds -data FoldingRangeKind = FoldingRangeComment - -- ^ Folding range for a comment - | FoldingRangeImports - -- ^ Folding range for a imports or includes - | FoldingRangeRegion - -- ^ Folding range for a region (e.g. #region) - | FoldingRangeUnknown Text - -- ^ Folding range that haskell-lsp-types does - -- not yet support - deriving (Read, Show, Eq) - -instance A.ToJSON FoldingRangeKind where - toJSON FoldingRangeComment = A.String "comment" - toJSON FoldingRangeImports = A.String "imports" - toJSON FoldingRangeRegion = A.String "region" - toJSON (FoldingRangeUnknown x) = A.String x - -instance A.FromJSON FoldingRangeKind where - parseJSON (A.String "comment") = pure FoldingRangeComment - parseJSON (A.String "imports") = pure FoldingRangeImports - parseJSON (A.String "region") = pure FoldingRangeRegion - parseJSON (A.String x) = pure (FoldingRangeUnknown x) - parseJSON _ = fail "FoldingRangeKind" - --- | Represents a folding range. -data FoldingRange = - FoldingRange - { -- | The zero-based line number from where the folded range starts. - _startLine :: UInt - -- | The zero-based character offset from where the folded range - -- starts. If not defined, defaults to the length of the start line. - , _startCharacter :: Maybe UInt - -- | The zero-based line number where the folded range ends. - , _endLine :: UInt - -- | The zero-based character offset before the folded range ends. - -- If not defined, defaults to the length of the end line. - , _endCharacter :: Maybe UInt - -- | Describes the kind of the folding range such as 'comment' or - -- 'region'. The kind is used to categorize folding ranges and used - -- by commands like 'Fold all comments'. See 'FoldingRangeKind' for - -- an enumeration of standardized kinds. - , _kind :: Maybe FoldingRangeKind - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''FoldingRange diff --git a/lsp-types/src/Language/LSP/Types/Formatting.hs b/lsp-types/src/Language/LSP/Types/Formatting.hs deleted file mode 100644 index 8bed6e734..000000000 --- a/lsp-types/src/Language/LSP/Types/Formatting.hs +++ /dev/null @@ -1,114 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} -module Language.LSP.Types.Formatting where - -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data DocumentFormattingClientCapabilities = - DocumentFormattingClientCapabilities - { -- | Whether formatting supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''DocumentFormattingClientCapabilities - -makeExtendingDatatype "DocumentFormattingOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DocumentFormattingOptions - -makeExtendingDatatype "DocumentFormattingRegistrationOptions" - [ ''TextDocumentRegistrationOptions, - ''DocumentFormattingOptions - ] - [] -deriveJSON lspOptions ''DocumentFormattingRegistrationOptions - --- | Value-object describing what options formatting should use. -data FormattingOptions = FormattingOptions - { -- | Size of a tab in spaces. - _tabSize :: UInt, - -- | Prefer spaces over tabs - _insertSpaces :: Bool, - -- | Trim trailing whitespace on a line. - -- - -- Since LSP 3.15.0 - _trimTrailingWhitespace :: Maybe Bool, - -- | Insert a newline character at the end of the file if one does not exist. - -- - -- Since LSP 3.15.0 - _insertFinalNewline :: Maybe Bool, - -- | Trim all newlines after the final newline at the end of the file. - -- - -- Since LSP 3.15.0 - _trimFinalNewlines :: Maybe Bool - -- Note: May be more properties - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''FormattingOptions -makeExtendingDatatype "DocumentFormattingParams" [''WorkDoneProgressParams] - [ ("_textDocument", [t| TextDocumentIdentifier |]) - , ("_options", [t| FormattingOptions |]) - ] -deriveJSON lspOptions ''DocumentFormattingParams - --- ------------------------------------- - -data DocumentRangeFormattingClientCapabilities = - DocumentRangeFormattingClientCapabilities - { -- | Whether formatting supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''DocumentRangeFormattingClientCapabilities - -makeExtendingDatatype "DocumentRangeFormattingOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''DocumentRangeFormattingOptions - -makeExtendingDatatype "DocumentRangeFormattingRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DocumentRangeFormattingOptions - ] - [] -deriveJSON lspOptions ''DocumentRangeFormattingRegistrationOptions - -makeExtendingDatatype "DocumentRangeFormattingParams" [''WorkDoneProgressParams] - [ ("_textDocument", [t| TextDocumentIdentifier |]) - , ("_range", [t| Range |]) - , ("_options", [t| FormattingOptions |]) - ] -deriveJSON lspOptions ''DocumentRangeFormattingParams - --- ------------------------------------- - -data DocumentOnTypeFormattingClientCapabilities = - DocumentOnTypeFormattingClientCapabilities - { -- | Whether formatting supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''DocumentOnTypeFormattingClientCapabilities - -data DocumentOnTypeFormattingOptions = - DocumentOnTypeFormattingOptions - { -- | A character on which formatting should be triggered, like @}@. - _firstTriggerCharacter :: Text - , -- | More trigger characters. - _moreTriggerCharacter :: Maybe [Text] - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''DocumentOnTypeFormattingOptions - -makeExtendingDatatype "DocumentOnTypeFormattingRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''DocumentOnTypeFormattingOptions - ] - [] -deriveJSON lspOptions ''DocumentOnTypeFormattingRegistrationOptions - -makeExtendingDatatype "DocumentOnTypeFormattingParams" [''TextDocumentPositionParams] - [ ("_ch", [t| Text |]) - , ("_options", [t| FormattingOptions |]) - ] -deriveJSON lspOptions ''DocumentOnTypeFormattingParams diff --git a/lsp-types/src/Language/LSP/Types/Hover.hs b/lsp-types/src/Language/LSP/Types/Hover.hs deleted file mode 100644 index 58fe24d5a..000000000 --- a/lsp-types/src/Language/LSP/Types/Hover.hs +++ /dev/null @@ -1,84 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} -module Language.LSP.Types.Hover where - -import Data.Aeson.TH -import Data.Text ( Text ) - -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.MarkupContent -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - - --- ------------------------------------- - -data HoverClientCapabilities = - HoverClientCapabilities - { _dynamicRegistration :: Maybe Bool - , _contentFormat :: Maybe (List MarkupKind) - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''HoverClientCapabilities - -makeExtendingDatatype "HoverOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''HoverOptions - -makeExtendingDatatype "HoverRegistrationOptions" [''TextDocumentRegistrationOptions, ''HoverOptions] [] -deriveJSON lspOptions ''HoverRegistrationOptions - -makeExtendingDatatype "HoverParams" [''TextDocumentPositionParams, ''WorkDoneProgressParams] [] -deriveJSON lspOptions ''HoverParams - --- ------------------------------------- - -data LanguageString = - LanguageString - { _language :: Text - , _value :: Text - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''LanguageString - -{-# DEPRECATED MarkedString, PlainString, CodeString "Use MarkupContent instead, since 3.3.0 (11/24/2017)" #-} -data MarkedString = - PlainString Text - | CodeString LanguageString - deriving (Eq,Read,Show) - -deriveJSON lspOptionsUntagged ''MarkedString - --- ------------------------------------- - -data HoverContents = - HoverContentsMS (List MarkedString) - | HoverContents MarkupContent - deriving (Read,Show,Eq) - -deriveJSON lspOptionsUntagged ''HoverContents - --- ------------------------------------- - -instance Semigroup HoverContents where - HoverContents h1 <> HoverContents h2 = HoverContents (h1 `mappend` h2) - HoverContents h1 <> HoverContentsMS (List h2s) = HoverContents (mconcat (h1: (map toMarkupContent h2s))) - HoverContentsMS (List h1s) <> HoverContents h2 = HoverContents (mconcat ((map toMarkupContent h1s) ++ [h2])) - HoverContentsMS (List h1s) <> HoverContentsMS (List h2s) = HoverContentsMS (List (h1s `mappend` h2s)) - -instance Monoid HoverContents where - mempty = HoverContentsMS (List []) - -toMarkupContent :: MarkedString -> MarkupContent -toMarkupContent (PlainString s) = unmarkedUpContent s -toMarkupContent (CodeString (LanguageString lang s)) = markedUpContent lang s - --- ------------------------------------- - -data Hover = - Hover - { _contents :: HoverContents - , _range :: Maybe Range - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''Hover diff --git a/lsp-types/src/Language/LSP/Types/Implementation.hs b/lsp-types/src/Language/LSP/Types/Implementation.hs deleted file mode 100644 index a36a29045..000000000 --- a/lsp-types/src/Language/LSP/Types/Implementation.hs +++ /dev/null @@ -1,42 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.Implementation where - -import Data.Aeson.TH -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data ImplementationClientCapabilities = ImplementationClientCapabilities - { -- | Whether implementation supports dynamic registration. If this is set - -- to 'True' - -- the client supports the new 'ImplementationRegistrationOptions' return - -- value for the corresponding server capability as well. - _dynamicRegistration :: Maybe Bool, - -- | The client supports additional metadata in the form of definition links. - -- - -- Since LSP 3.14.0 - _linkSupport :: Maybe Bool - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''ImplementationClientCapabilities - -makeExtendingDatatype "ImplementationOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''ImplementationOptions - -makeExtendingDatatype "ImplementationRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''ImplementationOptions - , ''StaticRegistrationOptions - ] [] -deriveJSON lspOptions ''ImplementationRegistrationOptions - -makeExtendingDatatype "ImplementationParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] [] -deriveJSON lspOptions ''ImplementationParams diff --git a/lsp-types/src/Language/LSP/Types/Initialize.hs b/lsp-types/src/Language/LSP/Types/Initialize.hs deleted file mode 100644 index 77247d10d..000000000 --- a/lsp-types/src/Language/LSP/Types/Initialize.hs +++ /dev/null @@ -1,96 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.Initialize where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import qualified Data.Text as T -import Language.LSP.Types.ClientCapabilities -import Language.LSP.Types.Common -import Language.LSP.Types.Progress -import Language.LSP.Types.ServerCapabilities -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils -import Language.LSP.Types.WorkspaceFolders - -data Trace = TraceOff | TraceMessages | TraceVerbose - deriving (Show, Read, Eq) - -instance ToJSON Trace where - toJSON TraceOff = String (T.pack "off") - toJSON TraceMessages = String (T.pack "messages") - toJSON TraceVerbose = String (T.pack "verbose") - -instance FromJSON Trace where - parseJSON (String s) = case T.unpack s of - "off" -> return TraceOff - "messages" -> return TraceMessages - "verbose" -> return TraceVerbose - _ -> fail "Trace" - parseJSON _ = fail "Trace" - -data ClientInfo = - ClientInfo - { -- | The name of the client as defined by the client. - _name :: Text - -- | The client's version as defined by the client. - , _version :: Maybe Text - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''ClientInfo - -makeExtendingDatatype "InitializeParams" [''WorkDoneProgressParams] - [ ("_processId", [t| Maybe Int32|]) - , ("_clientInfo", [t| Maybe ClientInfo |]) - , ("_rootPath", [t| Maybe Text |]) - , ("_rootUri", [t| Maybe Uri |]) - , ("_initializationOptions", [t| Maybe Value |]) - , ("_capabilities", [t| ClientCapabilities |]) - , ("_trace", [t| Maybe Trace |]) - , ("_workspaceFolders", [t| Maybe (List WorkspaceFolder) |]) - ] - -deriveJSON lspOptions ''InitializeParams - -data InitializeError = - InitializeError - { _retry :: Bool - } deriving (Read, Show, Eq) - -deriveJSON lspOptions ''InitializeError - -data ServerInfo = - ServerInfo - { -- | The name of the server as defined by the server. - _name :: Text - -- | The server's version as defined by the server. - , _version :: Maybe Text - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''ServerInfo - -data InitializeResult = - InitializeResult - { -- | The capabilities the language server provides. - _capabilities :: ServerCapabilities - -- | Information about the server. - -- Since LSP 3.15.0 - , _serverInfo :: Maybe ServerInfo - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''InitializeResult - --- --------------------------------------------------------------------- - -data InitializedParams = - InitializedParams - { - } deriving (Show, Read, Eq) - -instance FromJSON InitializedParams where - parseJSON (Object _) = pure InitializedParams - parseJSON _ = fail "InitializedParams" - -instance ToJSON InitializedParams where - toJSON InitializedParams = Object mempty - diff --git a/lsp-types/src/Language/LSP/Types/Internal/Generated.hs b/lsp-types/src/Language/LSP/Types/Internal/Generated.hs new file mode 100644 index 000000000..0dfd134a4 --- /dev/null +++ b/lsp-types/src/Language/LSP/Types/Internal/Generated.hs @@ -0,0 +1,34 @@ +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE PolyKinds #-} +{-# LANGUAGE QuantifiedConstraints #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE StandaloneKindSignatures #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} + +{-# OPTIONS_GHC -ddump-splices -ddump-to-file -dsuppress-uniques -dsuppress-coercions -dsuppress-type-applications -dsuppress-unfoldings -dsuppress-idinfo -dppr-cols=200 -dumpdir /tmp/dumps #-} + +-- This is a VERY big module, probably don't open it in your IDE. +-- It can be very useful to inspect the output of this with `-ddump-splices`, +-- I recommend also dumping it to a file. +module Language.LSP.Types.Internal.Generated where + +import Data.FileEmbed (makeRelativeToProject) +import Data.Row.Aeson () +import Language.LSP.MetaModel.CodeGen + +$(genMetaModelFromFile =<< makeRelativeToProject "metaModel.json") diff --git a/lsp-types/src/Language/LSP/Types/Internal/Lenses.hs b/lsp-types/src/Language/LSP/Types/Internal/Lenses.hs new file mode 100644 index 000000000..60e5dcf2b --- /dev/null +++ b/lsp-types/src/Language/LSP/Types/Internal/Lenses.hs @@ -0,0 +1,13 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} + +module Language.LSP.Types.Internal.Lenses where + +import Language.LSP.MetaModel.CodeGen (genLenses) +import Language.LSP.Types.Internal.Generated + +$(genLenses structNames) diff --git a/lsp-types/src/Language/LSP/Types/Lens.hs b/lsp-types/src/Language/LSP/Types/Lens.hs deleted file mode 100644 index 1b20b31d4..000000000 --- a/lsp-types/src/Language/LSP/Types/Lens.hs +++ /dev/null @@ -1,399 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE MultiParamTypeClasses #-} -{-# LANGUAGE FunctionalDependencies #-} -{-# LANGUAGE PolyKinds #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE ExplicitNamespaces #-} - -module Language.LSP.Types.Lens where - -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.Cancellation -import Language.LSP.Types.ClientCapabilities -import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.Command -import Language.LSP.Types.Common (type (|?)) -import Language.LSP.Types.Completion -import Language.LSP.Types.Configuration -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.Diagnostic -import Language.LSP.Types.DocumentFilter -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation -import Language.LSP.Types.Initialize -import Language.LSP.Types.Location -import Language.LSP.Types.MarkupContent -import Language.LSP.Types.Progress -import Language.LSP.Types.Registration -import Language.LSP.Types.References -import Language.LSP.Types.Rename -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.SelectionRange -import Language.LSP.Types.ServerCapabilities -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition -import Language.LSP.Types.Window -import Language.LSP.Types.WatchedFiles -import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types.WorkspaceFolders -import Language.LSP.Types.WorkspaceSymbol -import Language.LSP.Types.Message -import Language.LSP.Types.SemanticTokens -import Control.Lens.TH - --- TODO: This is out of date and very unmaintainable, use TH to call all these!! - --- client capabilities -makeFieldsNoPrefix ''MessageActionItemClientCapabilities -makeFieldsNoPrefix ''ShowMessageRequestClientCapabilities -makeFieldsNoPrefix ''ShowDocumentClientCapabilities -makeFieldsNoPrefix ''StaleRequestClientCapabilities -makeFieldsNoPrefix ''RegularExpressionsClientCapabilities -makeFieldsNoPrefix ''GeneralClientCapabilities -makeFieldsNoPrefix ''WorkspaceClientCapabilities -makeFieldsNoPrefix ''WindowClientCapabilities -makeFieldsNoPrefix ''ClientCapabilities - --- --------------------------------------------------------------------- - -makeFieldsNoPrefix ''SaveOptions -makeFieldsNoPrefix ''WorkspaceServerCapabilities -makeFieldsNoPrefix ''WorkspaceFoldersServerCapabilities -makeFieldsNoPrefix ''ServerCapabilities -makeFieldsNoPrefix ''Registration -makeFieldsNoPrefix ''RegistrationParams -makeFieldsNoPrefix ''Unregistration -makeFieldsNoPrefix ''UnregistrationParams -makeFieldsNoPrefix ''ParameterInformation -makeFieldsNoPrefix ''SignatureInformation -makeFieldsNoPrefix ''ApplyWorkspaceEditParams -makeFieldsNoPrefix ''ApplyWorkspaceEditResponseBody - --- --------------------------------------------------------------------- - --- Initialize -makeFieldsNoPrefix ''InitializeParams -makeFieldsNoPrefix ''InitializeError -makeFieldsNoPrefix ''InitializeResult -makeFieldsNoPrefix ''ClientInfo -makeFieldsNoPrefix ''ServerInfo -makeFieldsNoPrefix ''InitializedParams - --- Configuration -makeFieldsNoPrefix ''DidChangeConfigurationParams -makeFieldsNoPrefix ''ConfigurationItem -makeFieldsNoPrefix ''ConfigurationParams -makeFieldsNoPrefix ''DidChangeConfigurationClientCapabilities - --- Watched files -makeFieldsNoPrefix ''DidChangeWatchedFilesClientCapabilities -makeFieldsNoPrefix ''DidChangeWatchedFilesRegistrationOptions -makeFieldsNoPrefix ''FileSystemWatcher -makeFieldsNoPrefix ''WatchKind -makeFieldsNoPrefix ''FileEvent -makeFieldsNoPrefix ''DidChangeWatchedFilesParams - --- Workspace symbols -makeFieldsNoPrefix ''WorkspaceSymbolKindClientCapabilities -makeFieldsNoPrefix ''WorkspaceSymbolClientCapabilities -makeFieldsNoPrefix ''WorkspaceSymbolOptions -makeFieldsNoPrefix ''WorkspaceSymbolRegistrationOptions -makeFieldsNoPrefix ''WorkspaceSymbolParams - --- Location -makeFieldsNoPrefix ''Position -makeFieldsNoPrefix ''Range -makeFieldsNoPrefix ''Location -makeFieldsNoPrefix ''LocationLink - --- Markup -makeFieldsNoPrefix ''MarkupContent -makeFieldsNoPrefix ''MarkdownClientCapabilities - --- Completion -makeFieldsNoPrefix ''CompletionDoc -makeFieldsNoPrefix ''CompletionEdit -makeFieldsNoPrefix ''CompletionItem -makeFieldsNoPrefix ''CompletionContext -makeFieldsNoPrefix ''CompletionList -makeFieldsNoPrefix ''CompletionParams -makeFieldsNoPrefix ''CompletionOptions -makeFieldsNoPrefix ''CompletionRegistrationOptions -makeFieldsNoPrefix ''CompletionItemTagsClientCapabilities -makeFieldsNoPrefix ''CompletionItemResolveClientCapabilities -makeFieldsNoPrefix ''CompletionItemInsertTextModeClientCapabilities -makeFieldsNoPrefix ''CompletionItemClientCapabilities -makeFieldsNoPrefix ''CompletionItemKindClientCapabilities -makeFieldsNoPrefix ''CompletionClientCapabilities -makeFieldsNoPrefix ''InsertReplaceEdit - --- Declaration -makeFieldsNoPrefix ''DeclarationClientCapabilities -makeFieldsNoPrefix ''DeclarationOptions -makeFieldsNoPrefix ''DeclarationRegistrationOptions -makeFieldsNoPrefix ''DeclarationParams - --- CodeActions -makeFieldsNoPrefix ''CodeActionKindClientCapabilities -makeFieldsNoPrefix ''CodeActionLiteralSupport -makeFieldsNoPrefix ''CodeActionClientCapabilities -makeFieldsNoPrefix ''CodeActionResolveClientCapabilities -makeFieldsNoPrefix ''CodeActionOptions -makeFieldsNoPrefix ''CodeActionRegistrationOptions -makeFieldsNoPrefix ''CodeActionContext -makeFieldsNoPrefix ''CodeActionParams -makeFieldsNoPrefix ''CodeAction - --- CodeLens -makeFieldsNoPrefix ''CodeLensClientCapabilities -makeFieldsNoPrefix ''CodeLensOptions -makeFieldsNoPrefix ''CodeLensRegistrationOptions -makeFieldsNoPrefix ''CodeLensParams -makeFieldsNoPrefix ''CodeLens - --- DocumentLink -makeFieldsNoPrefix ''DocumentLinkClientCapabilities -makeFieldsNoPrefix ''DocumentLinkOptions -makeFieldsNoPrefix ''DocumentLinkRegistrationOptions -makeFieldsNoPrefix ''DocumentLinkParams -makeFieldsNoPrefix ''DocumentLink - --- DocumentColor -makeFieldsNoPrefix ''DocumentColorClientCapabilities -makeFieldsNoPrefix ''DocumentColorOptions -makeFieldsNoPrefix ''DocumentColorRegistrationOptions -makeFieldsNoPrefix ''DocumentColorParams -makeFieldsNoPrefix ''Color -makeFieldsNoPrefix ''ColorInformation - --- ColorPresentation -makeFieldsNoPrefix ''ColorPresentationParams -makeFieldsNoPrefix ''ColorPresentation - --- Formatting -makeFieldsNoPrefix ''DocumentFormattingClientCapabilities -makeFieldsNoPrefix ''DocumentFormattingOptions -makeFieldsNoPrefix ''DocumentFormattingRegistrationOptions -makeFieldsNoPrefix ''FormattingOptions -makeFieldsNoPrefix ''DocumentFormattingParams - --- RangeFormatting -makeFieldsNoPrefix ''DocumentRangeFormattingClientCapabilities -makeFieldsNoPrefix ''DocumentRangeFormattingOptions -makeFieldsNoPrefix ''DocumentRangeFormattingRegistrationOptions -makeFieldsNoPrefix ''DocumentRangeFormattingParams - --- OnTypeFormatting -makeFieldsNoPrefix ''DocumentOnTypeFormattingClientCapabilities -makeFieldsNoPrefix ''DocumentOnTypeFormattingOptions -makeFieldsNoPrefix ''DocumentOnTypeFormattingRegistrationOptions -makeFieldsNoPrefix ''DocumentOnTypeFormattingParams - --- Rename -makeFieldsNoPrefix ''RenameClientCapabilities -makeFieldsNoPrefix ''RenameOptions -makeFieldsNoPrefix ''RenameRegistrationOptions -makeFieldsNoPrefix ''RenameParams -makeFieldsNoPrefix ''PrepareSupportDefaultBehavior - --- PrepareRename -makeFieldsNoPrefix ''PrepareRenameParams -makeFieldsNoPrefix ''RangeWithPlaceholder - --- References -makeFieldsNoPrefix ''ReferencesClientCapabilities -makeFieldsNoPrefix ''ReferenceOptions -makeFieldsNoPrefix ''ReferenceRegistrationOptions -makeFieldsNoPrefix ''ReferenceContext -makeFieldsNoPrefix ''ReferenceParams - --- FoldingRange -makeFieldsNoPrefix ''FoldingRangeClientCapabilities -makeFieldsNoPrefix ''FoldingRangeOptions -makeFieldsNoPrefix ''FoldingRangeRegistrationOptions -makeFieldsNoPrefix ''FoldingRangeParams -makeFieldsNoPrefix ''FoldingRange - --- SelectionRange -makeFieldsNoPrefix ''SelectionRangeClientCapabilities -makeFieldsNoPrefix ''SelectionRangeOptions -makeFieldsNoPrefix ''SelectionRangeRegistrationOptions -makeFieldsNoPrefix ''SelectionRangeParams -makeFieldsNoPrefix ''SelectionRange - --- DocumentHighlight -makeFieldsNoPrefix ''DocumentHighlightClientCapabilities -makeFieldsNoPrefix ''DocumentHighlightOptions -makeFieldsNoPrefix ''DocumentHighlightRegistrationOptions -makeFieldsNoPrefix ''DocumentHighlightParams -makeFieldsNoPrefix ''DocumentHighlight - --- DocumentSymbol -makeFieldsNoPrefix ''DocumentSymbolKindClientCapabilities -makeFieldsNoPrefix ''DocumentSymbolClientCapabilities -makeFieldsNoPrefix ''DocumentSymbolOptions -makeFieldsNoPrefix ''DocumentSymbolRegistrationOptions -makeFieldsNoPrefix ''DocumentSymbolParams -makeFieldsNoPrefix ''DocumentSymbol -makeFieldsNoPrefix ''SymbolInformation - --- DocumentFilter -makeFieldsNoPrefix ''DocumentFilter - --- WorkspaceEdit -makeFieldsNoPrefix ''TextEdit -makeFieldsNoPrefix ''ChangeAnnotation -makeFieldsNoPrefix ''AnnotatedTextEdit -makeFieldsNoPrefix ''VersionedTextDocumentIdentifier -makeFieldsNoPrefix ''TextDocumentEdit -makeFieldsNoPrefix ''CreateFileOptions -makeFieldsNoPrefix ''CreateFile -makeFieldsNoPrefix ''RenameFileOptions -makeFieldsNoPrefix ''RenameFile -makeFieldsNoPrefix ''DeleteFileOptions -makeFieldsNoPrefix ''DeleteFile -makeFieldsNoPrefix ''WorkspaceEdit -makeFieldsNoPrefix ''WorkspaceEditClientCapabilities -makeFieldsNoPrefix ''WorkspaceEditChangeAnnotationClientCapabilities - --- Workspace Folders -makeFieldsNoPrefix ''WorkspaceFolder -makeFieldsNoPrefix ''WorkspaceFoldersChangeEvent -makeFieldsNoPrefix ''DidChangeWorkspaceFoldersParams - --- Message -makeFieldsNoPrefix ''RequestMessage -makeFieldsNoPrefix ''ResponseError -makeFieldsNoPrefix ''ResponseMessage -makeFieldsNoPrefix ''NotificationMessage -makeFieldsNoPrefix ''CancelParams - --- TextDocument -makeFieldsNoPrefix ''TextDocumentItem -makeFieldsNoPrefix ''TextDocumentIdentifier -makeFieldsNoPrefix ''TextDocumentPositionParams -makeFieldsNoPrefix ''TextDocumentSyncClientCapabilities -makeFieldsNoPrefix ''TextDocumentClientCapabilities -makeFieldsNoPrefix ''TextDocumentRegistrationOptions -makeFieldsNoPrefix ''TextDocumentSyncOptions -makeFieldsNoPrefix ''DidOpenTextDocumentParams -makeFieldsNoPrefix ''TextDocumentContentChangeEvent -makeFieldsNoPrefix ''DidChangeTextDocumentParams -makeFieldsNoPrefix ''TextDocumentChangeRegistrationOptions -makeFieldsNoPrefix ''WillSaveTextDocumentParams -makeFieldsNoPrefix ''DidSaveTextDocumentParams -makeFieldsNoPrefix ''TextDocumentSaveRegistrationOptions -makeFieldsNoPrefix ''DidCloseTextDocumentParams - --- Command -makeFieldsNoPrefix ''Command -makeFieldsNoPrefix ''ExecuteCommandParams -makeFieldsNoPrefix ''ExecuteCommandRegistrationOptions -makeFieldsNoPrefix ''ExecuteCommandClientCapabilities -makeFieldsNoPrefix ''ExecuteCommandOptions - --- Diagnostic -makeFieldsNoPrefix ''DiagnosticRelatedInformation -makeFieldsNoPrefix ''Diagnostic -makeFieldsNoPrefix ''PublishDiagnosticsTagsClientCapabilities -makeFieldsNoPrefix ''PublishDiagnosticsClientCapabilities -makeFieldsNoPrefix ''PublishDiagnosticsParams - --- Hover -makeFieldsNoPrefix ''HoverClientCapabilities -makeFieldsNoPrefix ''Hover -makeFieldsNoPrefix ''HoverParams -makeFieldsNoPrefix ''HoverOptions -makeFieldsNoPrefix ''HoverRegistrationOptions -makeFieldsNoPrefix ''LanguageString - --- Implementation -makeFieldsNoPrefix ''ImplementationClientCapabilities -makeFieldsNoPrefix ''ImplementationOptions -makeFieldsNoPrefix ''ImplementationRegistrationOptions -makeFieldsNoPrefix ''ImplementationParams - --- Definition -makeFieldsNoPrefix ''DefinitionOptions -makeFieldsNoPrefix ''DefinitionRegistrationOptions -makeFieldsNoPrefix ''DefinitionParams -makeFieldsNoPrefix ''DefinitionClientCapabilities - --- Type Definition -makeFieldsNoPrefix ''TypeDefinitionOptions -makeFieldsNoPrefix ''TypeDefinitionRegistrationOptions -makeFieldsNoPrefix ''TypeDefinitionParams -makeFieldsNoPrefix ''TypeDefinitionClientCapabilities - --- Window -makeFieldsNoPrefix ''ShowMessageParams -makeFieldsNoPrefix ''MessageActionItem -makeFieldsNoPrefix ''ShowMessageRequestParams -makeFieldsNoPrefix ''ShowDocumentParams -makeFieldsNoPrefix ''ShowDocumentResult -makeFieldsNoPrefix ''LogMessageParams -makeFieldsNoPrefix ''ProgressParams -makeFieldsNoPrefix ''WorkDoneProgressBeginParams -makeFieldsNoPrefix ''WorkDoneProgressReportParams -makeFieldsNoPrefix ''WorkDoneProgressEndParams -makeFieldsNoPrefix ''WorkDoneProgressCancelParams -makeFieldsNoPrefix ''WorkDoneProgressCreateParams -makeFieldsNoPrefix ''WorkDoneProgressOptions -makeFieldsNoPrefix ''WorkDoneProgressParams -makeFieldsNoPrefix ''PartialResultParams - --- Signature Help -makeFieldsNoPrefix ''SignatureHelpSignatureInformation -makeFieldsNoPrefix ''SignatureHelpParameterInformation -makeFieldsNoPrefix ''SignatureHelpParams -makeFieldsNoPrefix ''SignatureHelpClientCapabilities -makeFieldsNoPrefix ''SignatureHelpOptions -makeFieldsNoPrefix ''SignatureHelpRegistrationOptions -makeFieldsNoPrefix ''SignatureHelp - --- Static registration -makeFieldsNoPrefix ''StaticRegistrationOptions - --- Call hierarchy -makeFieldsNoPrefix ''CallHierarchyClientCapabilities -makeFieldsNoPrefix ''CallHierarchyOptions -makeFieldsNoPrefix ''CallHierarchyRegistrationOptions -makeFieldsNoPrefix ''CallHierarchyPrepareParams -makeFieldsNoPrefix ''CallHierarchyIncomingCallsParams -makeFieldsNoPrefix ''CallHierarchyIncomingCall -makeFieldsNoPrefix ''CallHierarchyOutgoingCallsParams -makeFieldsNoPrefix ''CallHierarchyOutgoingCall -makeFieldsNoPrefix ''CallHierarchyItem - --- Semantic tokens -makeFieldsNoPrefix ''SemanticTokensLegend -makeFieldsNoPrefix ''SemanticTokensDeltaClientCapabilities -makeFieldsNoPrefix ''SemanticTokensRequestsClientCapabilities -makeFieldsNoPrefix ''SemanticTokensClientCapabilities -makeFieldsNoPrefix ''SemanticTokensParams -makeFieldsNoPrefix ''SemanticTokensDeltaParams -makeFieldsNoPrefix ''SemanticTokensRangeParams -makeFieldsNoPrefix ''SemanticTokens -makeFieldsNoPrefix ''SemanticTokensPartialResult -makeFieldsNoPrefix ''SemanticTokensEdit -makeFieldsNoPrefix ''SemanticTokensDelta -makeFieldsNoPrefix ''SemanticTokensDeltaPartialResult -makeFieldsNoPrefix ''SemanticTokensWorkspaceClientCapabilities - --- Unions -makePrisms ''(|?) \ No newline at end of file diff --git a/lsp-types/src/Language/LSP/Types/Location.hs b/lsp-types/src/Language/LSP/Types/Location.hs index 3551502f5..9eafff5cc 100644 --- a/lsp-types/src/Language/LSP/Types/Location.hs +++ b/lsp-types/src/Language/LSP/Types/Location.hs @@ -1,94 +1,19 @@ -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE DuplicateRecordFields #-} module Language.LSP.Types.Location where -import Control.DeepSeq -import Data.Aeson.TH -import Data.Hashable -import GHC.Generics hiding (UInt) +import Control.Lens import Language.LSP.Types.Common -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils - --- --------------------------------------------------------------------- - --- | A position in a document. Note that the character offsets in a line --- are given in UTF-16 code units, *not* Unicode code points. -data Position = - Position - { -- | Line position in a document (zero-based). - _line :: UInt - -- | Character offset on a line in a document (zero-based). Assuming that - -- the line is represented as a string, the @character@ value represents the - -- gap between the @character@ and @character + 1@. - , _character :: UInt - } deriving (Show, Read, Eq, Ord, Generic) - -instance NFData Position -deriveJSON lspOptions ''Position - -instance Hashable Position - --- --------------------------------------------------------------------- - -data Range = - Range - { _start :: Position -- ^ The range's start position. (inclusive) - , _end :: Position -- ^ The range's end position. (exclusive, see: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#range ) - } deriving (Show, Read, Eq, Ord, Generic) - -instance NFData Range -deriveJSON lspOptions ''Range - -instance Hashable Range - --- --------------------------------------------------------------------- - -data Location = - Location - { _uri :: Uri - , _range :: Range - } deriving (Show, Read, Eq, Ord, Generic) - -instance NFData Location -deriveJSON lspOptions ''Location - -instance Hashable Location - --- --------------------------------------------------------------------- - --- | Represents a link between a source and a target location. -data LocationLink = - LocationLink - { -- | Span of the origin of this link. - -- Used as the underlined span for mouse interaction. Defaults to the word - -- range at the mouse position. - _originSelectionRange :: Maybe Range - -- | The target resource identifier of this link. - , _targetUri :: Uri - -- | The full target range of this link. If the target for example is a - -- symbol then target range is the range enclosing this symbol not including - -- leading/trailing whitespace but everything else like comments. This - -- information is typically used to highlight the range in the editor. - , _targetRange :: Range - -- | The range that should be selected and revealed when this link is being - -- followed, e.g the name of a function. Must be contained by the the - -- 'targetRange'. See also @DocumentSymbol._range@ - , _targetSelectionRange :: Range - } deriving (Read, Show, Eq) -deriveJSON lspOptions ''LocationLink - --- --------------------------------------------------------------------- +import Language.LSP.Types.Internal.Generated +import Language.LSP.Types.Internal.Lenses -- | A helper function for creating ranges. --- prop> mkRange l c l' c' = Range (Position l c) (Position l' c') mkRange :: UInt -> UInt -> UInt -> UInt -> Range mkRange l c l' c' = Range (Position l c) (Position l' c') -- | 'isSubrangeOf' returns true if for every 'Position' in the first 'Range', it's also in the second 'Range'. isSubrangeOf :: Range -> Range -> Bool -isSubrangeOf smallRange range = _start smallRange >= _start range && _end smallRange <= _end range +isSubrangeOf small big = small ^. start >= big ^. start && small ^. end <= big ^. end -- | 'positionInRange' returns true if the given 'Position' is in the 'Range'. positionInRange :: Position -> Range -> Bool -positionInRange p (Range sp ep) = sp <= p && p < ep -- Range's end position is exclusive. +positionInRange p (Range sp ep) = sp <= p && p < ep -- Range's end position is exclusive! diff --git a/lsp-types/src/Language/LSP/Types/LspId.hs b/lsp-types/src/Language/LSP/Types/LspId.hs index d61bf32e1..b024ba6b7 100644 --- a/lsp-types/src/Language/LSP/Types/LspId.hs +++ b/lsp-types/src/Language/LSP/Types/LspId.hs @@ -1,18 +1,16 @@ -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE TypeInType #-} -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeInType #-} module Language.LSP.Types.LspId where -import qualified Data.Aeson as A +import qualified Data.Aeson as A import Data.Hashable -import Data.Int (Int32) import Data.IxMap -import Data.Text (Text) +import Data.Text (Text) -import Language.LSP.Types.Method +import Language.LSP.Types.Common +import Language.LSP.Types.Internal.Generated -- | Id used for a request, Can be either a String or an Int data LspId (m :: Method f Request) = IdInt !Int32 | IdString !Text @@ -32,7 +30,7 @@ instance IxOrd LspId where toBase = SomeLspId instance Hashable (LspId m) where - hashWithSalt n (IdInt i) = hashWithSalt n i + hashWithSalt n (IdInt i) = hashWithSalt n i hashWithSalt n (IdString t) = hashWithSalt n t data SomeLspId where @@ -40,9 +38,9 @@ data SomeLspId where deriving instance Show SomeLspId instance Eq SomeLspId where - SomeLspId (IdInt a) == SomeLspId (IdInt b) = a == b + SomeLspId (IdInt a) == SomeLspId (IdInt b) = a == b SomeLspId (IdString a) == SomeLspId (IdString b) = a == b - _ == _ = False + _ == _ = False instance Ord SomeLspId where compare (SomeLspId x) (SomeLspId y) = go x y where diff --git a/lsp-types/src/Language/LSP/Types/MarkupContent.hs b/lsp-types/src/Language/LSP/Types/MarkupContent.hs index f4f1e40da..67bc407fa 100644 --- a/lsp-types/src/Language/LSP/Types/MarkupContent.hs +++ b/lsp-types/src/Language/LSP/Types/MarkupContent.hs @@ -1,87 +1,26 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE OverloadedStrings #-} --- | A MarkupContent literal represents a string value which content can --- be represented in different formats. --- Currently plaintext and markdown are supported formats. --- A MarkupContent is usually used in documentation properties of result --- literals like CompletionItem or SignatureInformation. +{-# OPTIONS_GHC -Wno-orphans #-} module Language.LSP.Types.MarkupContent where -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import qualified Data.Text as T -import Language.LSP.Types.Utils - --- | Describes the content type that a client supports in various --- result literals like `Hover`, `ParameterInfo` or `CompletionItem`. -data MarkupKind = MkPlainText -- ^ Plain text is supported as a content format - | MkMarkdown -- ^ Markdown is supported as a content format - deriving (Read, Show, Eq) - -instance ToJSON MarkupKind where - toJSON MkPlainText = String "plaintext" - toJSON MkMarkdown = String "markdown" - -instance FromJSON MarkupKind where - parseJSON (String "plaintext") = pure MkPlainText - parseJSON (String "markdown") = pure MkMarkdown - parseJSON _ = fail "MarkupKind" - --- | A `MarkupContent` literal represents a string value which content is interpreted base on its --- | kind flag. Currently the protocol supports `plaintext` and `markdown` as markup kinds. --- | --- | If the kind is `markdown` then the value can contain fenced code blocks like in GitHub issues. --- | See https://help.github.com/articles/creating-and-highlighting-code-blocks/#syntax-highlighting --- | --- | Here is an example how such a string can be constructed using JavaScript / TypeScript: --- | ```ts --- | let markdown: MarkdownContent = { --- | kind: MarkupKind.Markdown, --- | value: [ --- | '# Header', --- | 'Some text', --- | '```typescript', --- | 'someCode();', --- | '```' --- | ].join('\n') --- | }; --- | ``` --- | --- | *Please Note* that clients might sanitize the return markdown. A client could decide to --- | remove HTML from the markdown to avoid script execution. -data MarkupContent = - MarkupContent - { _kind :: MarkupKind -- ^ The type of the Markup - , _value :: Text -- ^ The content itself - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''MarkupContent - --- --------------------------------------------------------------------- +import Data.Text (Text) +import qualified Data.Text as T +import Language.LSP.Types.Internal.Generated -- | Create a 'MarkupContent' containing a quoted language string only. markedUpContent :: Text -> Text -> MarkupContent markedUpContent lang quote - = MarkupContent MkMarkdown ("\n```" <> lang <> "\n" <> quote <> "\n```\n") - --- --------------------------------------------------------------------- + = MarkupContent MarkupKind_Markdown ("\n```" <> lang <> "\n" <> quote <> "\n```\n") -- | Create a 'MarkupContent' containing unquoted text unmarkedUpContent :: Text -> MarkupContent -unmarkedUpContent str = MarkupContent MkPlainText str - --- --------------------------------------------------------------------- +unmarkedUpContent str = MarkupContent MarkupKind_PlainText str -- | Markdown for a section separator in Markdown, being a horizontal line sectionSeparator :: Text sectionSeparator = "* * *\n" --- --------------------------------------------------------------------- - -- | Given some plaintext, convert it into some equivalent markdown text. -- This is not *quite* the identity function. plainTextToMarkdown :: Text -> Text @@ -90,22 +29,10 @@ plainTextToMarkdown :: Text -> Text plainTextToMarkdown = T.unlines . fmap (<> " ") . T.lines instance Semigroup MarkupContent where - MarkupContent MkPlainText s1 <> MarkupContent MkPlainText s2 = MarkupContent MkPlainText (s1 `mappend` s2) - MarkupContent MkMarkdown s1 <> MarkupContent MkMarkdown s2 = MarkupContent MkMarkdown (s1 `mappend` s2) - MarkupContent MkPlainText s1 <> MarkupContent MkMarkdown s2 = MarkupContent MkMarkdown (plainTextToMarkdown s1 `mappend` s2) - MarkupContent MkMarkdown s1 <> MarkupContent MkPlainText s2 = MarkupContent MkMarkdown (s1 `mappend` plainTextToMarkdown s2) + MarkupContent MarkupKind_PlainText s1 <> MarkupContent MarkupKind_PlainText s2 = MarkupContent MarkupKind_PlainText (s1 `mappend` s2) + MarkupContent MarkupKind_Markdown s1 <> MarkupContent MarkupKind_Markdown s2 = MarkupContent MarkupKind_Markdown (s1 `mappend` s2) + MarkupContent MarkupKind_PlainText s1 <> MarkupContent MarkupKind_Markdown s2 = MarkupContent MarkupKind_Markdown (plainTextToMarkdown s1 `mappend` s2) + MarkupContent MarkupKind_Markdown s1 <> MarkupContent MarkupKind_PlainText s2 = MarkupContent MarkupKind_Markdown (s1 `mappend` plainTextToMarkdown s2) instance Monoid MarkupContent where - mempty = MarkupContent MkPlainText "" - --- --------------------------------------------------------------------- - --- | Client capabilities specific to the used markdown parser. --- @since 3.16.0 -data MarkdownClientCapabilities = - MarkdownClientCapabilities - { _parser :: Text - , _version :: Maybe Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''MarkdownClientCapabilities + mempty = MarkupContent MarkupKind_PlainText "" diff --git a/lsp-types/src/Language/LSP/Types/Message.hs b/lsp-types/src/Language/LSP/Types/Message.hs index da3c2a5ab..54d4e25f5 100644 --- a/lsp-types/src/Language/LSP/Types/Message.hs +++ b/lsp-types/src/Language/LSP/Types/Message.hs @@ -1,390 +1,154 @@ -{-# LANGUAGE GADTs #-} -{-# LANGUAGE TypeOperators #-} -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE ConstraintKinds #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE TupleSections #-} -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeInType #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE UndecidableInstances #-} module Language.LSP.Types.Message where -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.Cancellation -import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.Command import Language.LSP.Types.Common -import Language.LSP.Types.Configuration -import Language.LSP.Types.Completion -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.Diagnostic -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation -import Language.LSP.Types.Initialize -import Language.LSP.Types.Location +import Language.LSP.Types.Internal.Generated +import Language.LSP.Types.Internal.Lenses import Language.LSP.Types.LspId -import Language.LSP.Types.Method -import Language.LSP.Types.Progress -import Language.LSP.Types.Registration -import Language.LSP.Types.Rename -import Language.LSP.Types.References -import Language.LSP.Types.SelectionRange -import Language.LSP.Types.SemanticTokens -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition +import Language.LSP.Types.Method () import Language.LSP.Types.Utils -import Language.LSP.Types.Window -import Language.LSP.Types.WatchedFiles -import Language.LSP.Types.WorkspaceEdit -import Language.LSP.Types.WorkspaceFolders -import Language.LSP.Types.WorkspaceSymbol - -import Data.Kind -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Data.Scientific -import Data.String -import GHC.Generics --- --------------------------------------------------------------------- --- PARAMS definition --- Map Methods to params/responses --- --------------------------------------------------------------------- +import Control.Lens.TH +import Data.Aeson hiding (Null) +import qualified Data.Aeson as J +import Data.Aeson.TH +import Data.Kind +import Data.String (IsString (..)) +import Data.Text (Text) +import GHC.Generics +import GHC.TypeLits (KnownSymbol) + +-- 'RequestMessage', 'ResponseMessage', 'ResponseError', and 'NotificationMessage' +-- aren't present in the metamodel, although they should be. +-- https://github.com/microsoft/vscode-languageserver-node/issues/1079 + +-- | Notification message type as defined in the spec. +data NotificationMessage = + NotificationMessage + { _jsonrpc :: Text + , _method :: Text + , _params :: Maybe Value + } deriving (Show, Eq, Generic) --- | Map a method to the message payload type -type family MessageParams (m :: Method f t) :: Type where --- Client - -- General - MessageParams Initialize = InitializeParams - MessageParams Initialized = Maybe InitializedParams - MessageParams Shutdown = Empty - MessageParams Exit = Empty - -- Workspace - MessageParams WorkspaceDidChangeWorkspaceFolders = DidChangeWorkspaceFoldersParams - MessageParams WorkspaceDidChangeConfiguration = DidChangeConfigurationParams - MessageParams WorkspaceDidChangeWatchedFiles = DidChangeWatchedFilesParams - MessageParams WorkspaceSymbol = WorkspaceSymbolParams - MessageParams WorkspaceExecuteCommand = ExecuteCommandParams - -- Sync/Document state - MessageParams TextDocumentDidOpen = DidOpenTextDocumentParams - MessageParams TextDocumentDidChange = DidChangeTextDocumentParams - MessageParams TextDocumentWillSave = WillSaveTextDocumentParams - MessageParams TextDocumentWillSaveWaitUntil = WillSaveTextDocumentParams - MessageParams TextDocumentDidSave = DidSaveTextDocumentParams - MessageParams TextDocumentDidClose = DidCloseTextDocumentParams - -- Completion - MessageParams TextDocumentCompletion = CompletionParams - MessageParams CompletionItemResolve = CompletionItem - -- Language Queries - MessageParams TextDocumentHover = HoverParams - MessageParams TextDocumentSignatureHelp = SignatureHelpParams - MessageParams TextDocumentDeclaration = DeclarationParams - MessageParams TextDocumentDefinition = DefinitionParams - MessageParams TextDocumentTypeDefinition = TypeDefinitionParams - MessageParams TextDocumentImplementation = ImplementationParams - MessageParams TextDocumentReferences = ReferenceParams - MessageParams TextDocumentDocumentHighlight = DocumentHighlightParams - MessageParams TextDocumentDocumentSymbol = DocumentSymbolParams - -- Code Action/Lens/Link - MessageParams TextDocumentCodeAction = CodeActionParams - MessageParams TextDocumentCodeLens = CodeLensParams - MessageParams CodeLensResolve = CodeLens - MessageParams TextDocumentDocumentLink = DocumentLinkParams - MessageParams DocumentLinkResolve = DocumentLink - -- Syntax highlighting/coloring - MessageParams TextDocumentDocumentColor = DocumentColorParams - MessageParams TextDocumentColorPresentation = ColorPresentationParams - -- Formatting - MessageParams TextDocumentFormatting = DocumentFormattingParams - MessageParams TextDocumentRangeFormatting = DocumentRangeFormattingParams - MessageParams TextDocumentOnTypeFormatting = DocumentOnTypeFormattingParams - -- Rename - MessageParams TextDocumentRename = RenameParams - MessageParams TextDocumentPrepareRename = PrepareRenameParams - -- Folding Range - MessageParams TextDocumentFoldingRange = FoldingRangeParams - -- Selection Range - MessageParams TextDocumentSelectionRange = SelectionRangeParams - -- Call hierarchy - MessageParams TextDocumentPrepareCallHierarchy = CallHierarchyPrepareParams - MessageParams CallHierarchyIncomingCalls = CallHierarchyIncomingCallsParams - MessageParams CallHierarchyOutgoingCalls = CallHierarchyOutgoingCallsParams - -- Semantic tokens - MessageParams TextDocumentSemanticTokens = Empty - MessageParams TextDocumentSemanticTokensFull = SemanticTokensParams - MessageParams TextDocumentSemanticTokensFullDelta = SemanticTokensDeltaParams - MessageParams TextDocumentSemanticTokensRange = SemanticTokensRangeParams - MessageParams WorkspaceSemanticTokensRefresh = Empty --- Server - -- Window - MessageParams WindowShowMessage = ShowMessageParams - MessageParams WindowShowMessageRequest = ShowMessageRequestParams - MessageParams WindowShowDocument = ShowDocumentParams - MessageParams WindowLogMessage = LogMessageParams - -- Progress - MessageParams WindowWorkDoneProgressCreate = WorkDoneProgressCreateParams - MessageParams WindowWorkDoneProgressCancel = WorkDoneProgressCancelParams - MessageParams Progress = ProgressParams SomeProgressParams - -- Telemetry - MessageParams TelemetryEvent = Value - -- Client - MessageParams ClientRegisterCapability = RegistrationParams - MessageParams ClientUnregisterCapability = UnregistrationParams - -- Workspace - MessageParams WorkspaceWorkspaceFolders = Empty - MessageParams WorkspaceConfiguration = ConfigurationParams - MessageParams WorkspaceApplyEdit = ApplyWorkspaceEditParams - -- Document/Diagnostic - MessageParams TextDocumentPublishDiagnostics = PublishDiagnosticsParams - -- Cancel - MessageParams CancelRequest = CancelParams - -- Custom - MessageParams CustomMethod = Value - --- | Map a request method to the response payload type -type family ResponseResult (m :: Method f Request) :: Type where --- Even though the specification mentions that the result types are --- @x | y | ... | null@, they don't actually need to be wrapped in a Maybe since --- (we think) this is just to account for how the response field is always --- nullable. I.e. if it is null, then the error field is set - --- Client - -- General - ResponseResult Initialize = InitializeResult - ResponseResult Shutdown = Empty - -- Workspace - ResponseResult WorkspaceSymbol = List SymbolInformation - ResponseResult WorkspaceExecuteCommand = Value - -- Sync/Document state - ResponseResult TextDocumentWillSaveWaitUntil = List TextEdit - -- Completion - ResponseResult TextDocumentCompletion = List CompletionItem |? CompletionList - ResponseResult CompletionItemResolve = CompletionItem - -- Language Queries - ResponseResult TextDocumentHover = Maybe Hover - ResponseResult TextDocumentSignatureHelp = SignatureHelp - ResponseResult TextDocumentDeclaration = Location |? List Location |? List LocationLink - ResponseResult TextDocumentDefinition = Location |? List Location |? List LocationLink - ResponseResult TextDocumentTypeDefinition = Location |? List Location |? List LocationLink - ResponseResult TextDocumentImplementation = Location |? List Location |? List LocationLink - ResponseResult TextDocumentReferences = List Location - ResponseResult TextDocumentDocumentHighlight = List DocumentHighlight - ResponseResult TextDocumentDocumentSymbol = List DocumentSymbol |? List SymbolInformation - -- Code Action/Lens/Link - ResponseResult TextDocumentCodeAction = List (Command |? CodeAction) - ResponseResult TextDocumentCodeLens = List CodeLens - ResponseResult CodeLensResolve = CodeLens - ResponseResult TextDocumentDocumentLink = List DocumentLink - ResponseResult DocumentLinkResolve = DocumentLink - -- Syntax highlighting/coloring - ResponseResult TextDocumentDocumentColor = List ColorInformation - ResponseResult TextDocumentColorPresentation = List ColorPresentation - -- Formatting - ResponseResult TextDocumentFormatting = List TextEdit - ResponseResult TextDocumentRangeFormatting = List TextEdit - ResponseResult TextDocumentOnTypeFormatting = List TextEdit - -- Rename - ResponseResult TextDocumentRename = WorkspaceEdit - ResponseResult TextDocumentPrepareRename = Maybe (Range |? RangeWithPlaceholder) - -- FoldingRange - ResponseResult TextDocumentFoldingRange = List FoldingRange - ResponseResult TextDocumentSelectionRange = List SelectionRange - -- Call hierarchy - ResponseResult TextDocumentPrepareCallHierarchy = Maybe (List CallHierarchyItem) - ResponseResult CallHierarchyIncomingCalls = Maybe (List CallHierarchyIncomingCall) - ResponseResult CallHierarchyOutgoingCalls = Maybe (List CallHierarchyOutgoingCall) - -- Semantic tokens - ResponseResult TextDocumentSemanticTokens = Empty - ResponseResult TextDocumentSemanticTokensFull = Maybe SemanticTokens - ResponseResult TextDocumentSemanticTokensFullDelta = Maybe (SemanticTokens |? SemanticTokensDelta) - ResponseResult TextDocumentSemanticTokensRange = Maybe SemanticTokens - ResponseResult WorkspaceSemanticTokensRefresh = Empty - -- Custom can be either a notification or a message --- Server - -- Window - ResponseResult WindowShowMessageRequest = Maybe MessageActionItem - ResponseResult WindowShowDocument = ShowDocumentResult - ResponseResult WindowWorkDoneProgressCreate = Empty - -- Capability - ResponseResult ClientRegisterCapability = Empty - ResponseResult ClientUnregisterCapability = Empty - -- Workspace - ResponseResult WorkspaceWorkspaceFolders = Maybe (List WorkspaceFolder) - ResponseResult WorkspaceConfiguration = List Value - ResponseResult WorkspaceApplyEdit = ApplyWorkspaceEditResponseBody --- Custom - ResponseResult CustomMethod = Value +deriveJSON lspOptions ''NotificationMessage +-- This isn't present in the metamodel. +-- | Request message type as defined in the spec. +data RequestMessage = RequestMessage + { _jsonrpc :: Text + , _id :: Int32 |? Text + , _method :: Text + , _params :: Maybe Value + } deriving (Show, Eq, Generic) --- --------------------------------------------------------------------- -{- -$ Notifications and Requests +deriveJSON lspOptions ''RequestMessage -Notification and requests ids starting with '$/' are messages which are protocol -implementation dependent and might not be implementable in all clients or -servers. For example if the server implementation uses a single threaded -synchronous programming language then there is little a server can do to react -to a '$/cancelRequest'. If a server or client receives notifications or requests -starting with '$/' it is free to ignore them if they are unknown. +-- | Response error type as defined in the spec. +data ResponseError = + ResponseError + { _code :: ErrorCodes + , _message :: Text + , _xdata :: Maybe Value + } deriving (Show, Eq, Generic) --} +deriveJSON lspOptions ''ResponseError -data NotificationMessage (m :: Method f Notification) = - NotificationMessage +-- | Response message type as defined in the spec. +data ResponseMessage = + ResponseMessage + { _jsonrpc :: Text + , _id :: Int32 |? Text |? Null + , _result :: Maybe Value + , _error :: Maybe ResponseError + } deriving (Show, Eq, Generic) + +deriveJSON lspOptions ''ResponseMessage + +----- +-- | Typed notification message, containing the correct parameter payload. +data TNotificationMessage (m :: Method f Notification) = + TNotificationMessage { _jsonrpc :: Text , _method :: SMethod m , _params :: MessageParams m } deriving Generic -deriving instance Eq (MessageParams m) => Eq (NotificationMessage m) -deriving instance Show (MessageParams m) => Show (NotificationMessage m) +deriving instance Eq (MessageParams m) => Eq (TNotificationMessage m) +deriving instance Show (MessageParams m) => Show (TNotificationMessage m) -instance (FromJSON (MessageParams m), FromJSON (SMethod m)) => FromJSON (NotificationMessage m) where - parseJSON = genericParseJSON lspOptions . addNullField "params" -instance (ToJSON (MessageParams m)) => ToJSON (NotificationMessage m) where +instance (FromJSON (MessageParams m), FromJSON (SMethod m)) => FromJSON (TNotificationMessage m) where + parseJSON = genericParseJSON lspOptions +instance (ToJSON (MessageParams m)) => ToJSON (TNotificationMessage m) where toJSON = genericToJSON lspOptions toEncoding = genericToEncoding lspOptions -data RequestMessage (m :: Method f Request) = RequestMessage +-- | Typed request message, containing hte correct parameter payload. +data TRequestMessage (m :: Method f Request) = TRequestMessage { _jsonrpc :: Text , _id :: LspId m , _method :: SMethod m , _params :: MessageParams m } deriving Generic -deriving instance Eq (MessageParams m) => Eq (RequestMessage m) -deriving instance (Read (SMethod m), Read (MessageParams m)) => Read (RequestMessage m) -deriving instance Show (MessageParams m) => Show (RequestMessage m) - --- | Replace a missing field in an object with a null field, to simplify parsing --- This is a hack to allow other types than Maybe to work like Maybe in allowing the field to be missing. --- See also this issue: https://github.com/haskell/aeson/issues/646 -addNullField :: String -> Value -> Value -addNullField s (Object o) = Object $ o <> fromString s .= Null -addNullField _ v = v +deriving instance Eq (MessageParams m) => Eq (TRequestMessage m) +deriving instance Show (MessageParams m) => Show (TRequestMessage m) -instance (FromJSON (MessageParams m), FromJSON (SMethod m)) => FromJSON (RequestMessage m) where +instance (FromJSON (MessageParams m), FromJSON (SMethod m)) => FromJSON (TRequestMessage m) where parseJSON = genericParseJSON lspOptions . addNullField "params" -instance (ToJSON (MessageParams m), FromJSON (SMethod m)) => ToJSON (RequestMessage m) where +instance (ToJSON (MessageParams m)) => ToJSON (TRequestMessage m) where toJSON = genericToJSON lspOptions toEncoding = genericToEncoding lspOptions --- | A custom message data type is needed to distinguish between --- notifications and requests, since a CustomMethod can be both! -data CustomMessage f t where - ReqMess :: RequestMessage (CustomMethod :: Method f Request) -> CustomMessage f Request - NotMess :: NotificationMessage (CustomMethod :: Method f Notification) -> CustomMessage f Notification - -deriving instance Show (CustomMessage p t) - -instance ToJSON (CustomMessage p t) where - toJSON (ReqMess a) = toJSON a - toJSON (NotMess a) = toJSON a - -instance FromJSON (CustomMessage p Request) where - parseJSON v = ReqMess <$> parseJSON v -instance FromJSON (CustomMessage p Notification) where - parseJSON v = NotMess <$> parseJSON v - --- --------------------------------------------------------------------- --- Response Message --- --------------------------------------------------------------------- +data TResponseError (m :: Method f Request) = + TResponseError + { _code :: ErrorCodes + , _message :: Text + , _xdata :: Maybe (ErrorData m) + } deriving Generic -data ErrorCode = ParseError - | InvalidRequest - | MethodNotFound - | InvalidParams - | InternalError - | ServerErrorStart - | ServerErrorEnd - | ServerNotInitialized - | UnknownErrorCode - | RequestCancelled - | ContentModified - | ServerCancelled - | RequestFailed - | ErrorCodeCustom Int32 - -- ^ Note: server error codes are reserved from -32099 to -32000 - deriving (Read,Show,Eq) - -instance ToJSON ErrorCode where - toJSON ParseError = Number (-32700) - toJSON InvalidRequest = Number (-32600) - toJSON MethodNotFound = Number (-32601) - toJSON InvalidParams = Number (-32602) - toJSON InternalError = Number (-32603) - toJSON ServerErrorStart = Number (-32099) - toJSON ServerErrorEnd = Number (-32000) - toJSON ServerNotInitialized = Number (-32002) - toJSON UnknownErrorCode = Number (-32001) - toJSON RequestCancelled = Number (-32800) - toJSON ContentModified = Number (-32801) - toJSON ServerCancelled = Number (-32802) - toJSON RequestFailed = Number (-32803) - toJSON (ErrorCodeCustom n) = Number (fromIntegral n) - -instance FromJSON ErrorCode where - parseJSON (Number (-32700)) = pure ParseError - parseJSON (Number (-32600)) = pure InvalidRequest - parseJSON (Number (-32601)) = pure MethodNotFound - parseJSON (Number (-32602)) = pure InvalidParams - parseJSON (Number (-32603)) = pure InternalError - parseJSON (Number (-32099)) = pure ServerErrorStart - parseJSON (Number (-32000)) = pure ServerErrorEnd - parseJSON (Number (-32002)) = pure ServerNotInitialized - parseJSON (Number (-32001)) = pure UnknownErrorCode - parseJSON (Number (-32800)) = pure RequestCancelled - parseJSON (Number (-32801)) = pure ContentModified - parseJSON (Number (-32802)) = pure ServerCancelled - parseJSON (Number (-32803)) = pure RequestFailed - parseJSON (Number n ) = case toBoundedInteger n of - Just i -> pure (ErrorCodeCustom i) - Nothing -> fail "Couldn't convert ErrorCode to bounded integer." - parseJSON _ = fail "Couldn't parse ErrorCode" - --- ------------------------------------- +deriving instance Eq (ErrorData m) => Eq (TResponseError m) +deriving instance Show (ErrorData m) => Show (TResponseError m) -data ResponseError = - ResponseError - { _code :: ErrorCode - , _message :: Text - , _xdata :: Maybe Value - } deriving (Read,Show,Eq) +instance (FromJSON (ErrorData m)) => FromJSON (TResponseError m) where + parseJSON = genericParseJSON lspOptions +instance (ToJSON (ErrorData m)) => ToJSON (TResponseError m) where + toJSON = genericToJSON lspOptions + toEncoding = genericToEncoding lspOptions -deriveJSON lspOptions ''ResponseError +-- TODO: similar functions for the others? +toUntypedResponseError :: (ToJSON (ErrorData m)) => TResponseError m -> ResponseError +toUntypedResponseError (TResponseError c m d) = ResponseError c m (fmap toJSON d) --- | Either result or error must be Just. -data ResponseMessage (m :: Method f Request) = - ResponseMessage +-- | A typed response message with a correct result payload. +data TResponseMessage (m :: Method f Request) = + TResponseMessage { _jsonrpc :: Text , _id :: Maybe (LspId m) - , _result :: Either ResponseError (ResponseResult m) + , _result :: Either (TResponseError m) (MessageResult m) } deriving Generic -deriving instance Eq (ResponseResult m) => Eq (ResponseMessage m) -deriving instance Read (ResponseResult m) => Read (ResponseMessage m) -deriving instance Show (ResponseResult m) => Show (ResponseMessage m) +deriving instance (Eq (MessageResult m), Eq (ErrorData m)) => Eq (TResponseMessage m) +deriving instance (Show (MessageResult m), Show (ErrorData m)) => Show (TResponseMessage m) -instance (ToJSON (ResponseResult m)) => ToJSON (ResponseMessage m) where - toJSON ResponseMessage { _jsonrpc = jsonrpc, _id = lspid, _result = result } +instance (ToJSON (MessageResult m), ToJSON (ErrorData m)) => ToJSON (TResponseMessage m) where + toJSON TResponseMessage { _jsonrpc = jsonrpc, _id = lspid, _result = result } = object [ "jsonrpc" .= jsonrpc , "id" .= lspid @@ -393,7 +157,7 @@ instance (ToJSON (ResponseResult m)) => ToJSON (ResponseMessage m) where Right a -> "result" .= a ] -instance FromJSON (ResponseResult a) => FromJSON (ResponseMessage a) where +instance (FromJSON (MessageResult a), FromJSON (ErrorData a)) => FromJSON (TResponseMessage a) where parseJSON = withObject "Response" $ \o -> do _jsonrpc <- o .: "jsonrpc" _id <- o .: "id" @@ -405,19 +169,53 @@ instance FromJSON (ResponseResult a) => FromJSON (ResponseMessage a) where (Nothing, Just res) -> pure $ Right res (Just _err, Just _res) -> fail $ "both error and result cannot be present: " ++ show o (Nothing, Nothing) -> fail "both error and result cannot be Nothing" - return $ ResponseMessage _jsonrpc _id result + return $ TResponseMessage _jsonrpc _id result + +-- | A typed custom message. A special data type is needed to distinguish between +-- notifications and requests, since a CustomMethod can be both! +data TCustomMessage s f t where + ReqMess :: TRequestMessage (Method_CustomMethod s :: Method f Request) -> TCustomMessage s f Request + NotMess :: TNotificationMessage (Method_CustomMethod s :: Method f Notification) -> TCustomMessage s f Notification + +deriving instance Show (TCustomMessage s f t) + +instance ToJSON (TCustomMessage s f t) where + toJSON (ReqMess a) = toJSON a + toJSON (NotMess a) = toJSON a + +instance KnownSymbol s => FromJSON (TCustomMessage s f Request) where + parseJSON v = ReqMess <$> parseJSON v +instance KnownSymbol s => FromJSON (TCustomMessage s f Notification) where + parseJSON v = NotMess <$> parseJSON v + -- --------------------------------------------------------------------- -- Helper Type Families -- --------------------------------------------------------------------- -- | Map a method to the Request/Notification type with the correct --- payload -type family Message (m :: Method f t) :: Type where - Message (CustomMethod :: Method f t) = CustomMessage f t - Message (m :: Method f Request) = RequestMessage m - Message (m :: Method f Notification) = NotificationMessage m +-- payload. +type family TMessage (m :: Method f t) :: Type where + TMessage (Method_CustomMethod s :: Method f t) = TCustomMessage s f t + TMessage (m :: Method f Request) = TRequestMessage m + TMessage (m :: Method f Notification) = TNotificationMessage m -- Some helpful type synonyms -type ClientMessage (m :: Method FromClient t) = Message m -type ServerMessage (m :: Method FromServer t) = Message m +type TClientMessage (m :: Method ClientToServer t) = TMessage m +type TServerMessage (m :: Method ServerToClient t) = TMessage m + +-- | Replace a missing field in an object with a null field, to simplify parsing +-- This is a hack to allow other types than Maybe to work like Maybe in allowing the field to be missing. +-- See also this issue: https://github.com/haskell/aeson/issues/646 +addNullField :: String -> Value -> Value +addNullField s (Object o) = Object $ o <> fromString s .= J.Null +addNullField _ v = v + +makeFieldsNoPrefix ''RequestMessage +makeFieldsNoPrefix ''ResponseMessage +makeFieldsNoPrefix ''NotificationMessage +makeFieldsNoPrefix ''ResponseError +makeFieldsNoPrefix ''TRequestMessage +makeFieldsNoPrefix ''TResponseMessage +makeFieldsNoPrefix ''TNotificationMessage +makeFieldsNoPrefix ''TResponseError diff --git a/lsp-types/src/Language/LSP/Types/Method.hs b/lsp-types/src/Language/LSP/Types/Method.hs index 52baa796c..1c1664989 100644 --- a/lsp-types/src/Language/LSP/Types/Method.hs +++ b/lsp-types/src/Language/LSP/Types/Method.hs @@ -1,191 +1,39 @@ -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE MagicHash #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE MagicHash #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE StandaloneKindSignatures #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeInType #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE QuantifiedConstraints #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE UndecidableSuperClasses #-} +{-# LANGUAGE FlexibleContexts #-} + +{-# OPTIONS_GHC -Wno-orphans #-} module Language.LSP.Types.Method where -import qualified Data.Aeson as A import Data.Aeson.Types -import Data.Text (Text) +import Data.Function (on) +import Data.GADT.Compare +import Data.Proxy +import Data.Type.Equality +import GHC.Exts (Int (..), dataToTag#) +import GHC.TypeLits (KnownSymbol, sameSymbol, + symbolVal) +import Language.LSP.Types.Common +import Language.LSP.Types.Internal.Generated import Language.LSP.Types.Utils -import Data.Function (on) -import Control.Applicative -import Data.GADT.Compare -import Data.Type.Equality -import GHC.Exts (Int(..), dataToTag#) -import Unsafe.Coerce - --- --------------------------------------------------------------------- - -data From = FromServer | FromClient -data MethodType = Notification | Request - -data Method (f :: From) (t :: MethodType) where --- Client Methods - -- General - Initialize :: Method FromClient Request - Initialized :: Method FromClient Notification - Shutdown :: Method FromClient Request - Exit :: Method FromClient Notification - -- Workspace - WorkspaceDidChangeWorkspaceFolders :: Method FromClient Notification - WorkspaceDidChangeConfiguration :: Method FromClient Notification - WorkspaceDidChangeWatchedFiles :: Method FromClient Notification - WorkspaceSymbol :: Method FromClient Request - WorkspaceExecuteCommand :: Method FromClient Request - -- Document - TextDocumentDidOpen :: Method FromClient Notification - TextDocumentDidChange :: Method FromClient Notification - TextDocumentWillSave :: Method FromClient Notification - TextDocumentWillSaveWaitUntil :: Method FromClient Request - TextDocumentDidSave :: Method FromClient Notification - TextDocumentDidClose :: Method FromClient Notification - -- Completion - TextDocumentCompletion :: Method FromClient Request - CompletionItemResolve :: Method FromClient Request - -- LanguageQueries - TextDocumentHover :: Method FromClient Request - TextDocumentSignatureHelp :: Method FromClient Request - TextDocumentDeclaration :: Method FromClient Request - TextDocumentDefinition :: Method FromClient Request - TextDocumentTypeDefinition :: Method FromClient Request - TextDocumentImplementation :: Method FromClient Request - TextDocumentReferences :: Method FromClient Request - TextDocumentDocumentHighlight :: Method FromClient Request - TextDocumentDocumentSymbol :: Method FromClient Request - -- Code Action/Lens/Link - TextDocumentCodeAction :: Method FromClient Request - TextDocumentCodeLens :: Method FromClient Request - CodeLensResolve :: Method FromClient Request - TextDocumentDocumentLink :: Method FromClient Request - DocumentLinkResolve :: Method FromClient Request - -- Syntax highlighting/Coloring - TextDocumentDocumentColor :: Method FromClient Request - TextDocumentColorPresentation :: Method FromClient Request - -- Formatting - TextDocumentFormatting :: Method FromClient Request - TextDocumentRangeFormatting :: Method FromClient Request - TextDocumentOnTypeFormatting :: Method FromClient Request - -- Rename - TextDocumentRename :: Method FromClient Request - TextDocumentPrepareRename :: Method FromClient Request - -- FoldingRange - TextDocumentFoldingRange :: Method FromClient Request - TextDocumentSelectionRange :: Method FromClient Request - -- Call hierarchy - TextDocumentPrepareCallHierarchy :: Method FromClient Request - CallHierarchyIncomingCalls :: Method FromClient Request - CallHierarchyOutgoingCalls :: Method FromClient Request - -- SemanticTokens - TextDocumentSemanticTokens :: Method FromClient Request - TextDocumentSemanticTokensFull :: Method FromClient Request - TextDocumentSemanticTokensFullDelta :: Method FromClient Request - TextDocumentSemanticTokensRange :: Method FromClient Request - --- ServerMethods - -- Window - WindowShowMessage :: Method FromServer Notification - WindowShowMessageRequest :: Method FromServer Request - WindowShowDocument :: Method FromServer Request - WindowLogMessage :: Method FromServer Notification - WindowWorkDoneProgressCancel :: Method FromClient Notification - WindowWorkDoneProgressCreate :: Method FromServer Request - -- Progress - Progress :: Method FromServer Notification - -- Telemetry - TelemetryEvent :: Method FromServer Notification - -- Client - ClientRegisterCapability :: Method FromServer Request - ClientUnregisterCapability :: Method FromServer Request - -- Workspace - WorkspaceWorkspaceFolders :: Method FromServer Request - WorkspaceConfiguration :: Method FromServer Request - WorkspaceApplyEdit :: Method FromServer Request - WorkspaceSemanticTokensRefresh :: Method FromServer Request - -- Document - TextDocumentPublishDiagnostics :: Method FromServer Notification - --- Cancelling - CancelRequest :: Method f Notification - --- Custom - -- A custom message type. It is not enforced that this starts with $/. - CustomMethod :: Method f t - -data SMethod (m :: Method f t) where - SInitialize :: SMethod Initialize - SInitialized :: SMethod Initialized - SShutdown :: SMethod Shutdown - SExit :: SMethod Exit - SWorkspaceDidChangeWorkspaceFolders :: SMethod WorkspaceDidChangeWorkspaceFolders - SWorkspaceDidChangeConfiguration :: SMethod WorkspaceDidChangeConfiguration - SWorkspaceDidChangeWatchedFiles :: SMethod WorkspaceDidChangeWatchedFiles - SWorkspaceSymbol :: SMethod WorkspaceSymbol - SWorkspaceExecuteCommand :: SMethod WorkspaceExecuteCommand - STextDocumentDidOpen :: SMethod TextDocumentDidOpen - STextDocumentDidChange :: SMethod TextDocumentDidChange - STextDocumentWillSave :: SMethod TextDocumentWillSave - STextDocumentWillSaveWaitUntil :: SMethod TextDocumentWillSaveWaitUntil - STextDocumentDidSave :: SMethod TextDocumentDidSave - STextDocumentDidClose :: SMethod TextDocumentDidClose - STextDocumentCompletion :: SMethod TextDocumentCompletion - SCompletionItemResolve :: SMethod CompletionItemResolve - STextDocumentHover :: SMethod TextDocumentHover - STextDocumentSignatureHelp :: SMethod TextDocumentSignatureHelp - STextDocumentDeclaration :: SMethod TextDocumentDeclaration - STextDocumentDefinition :: SMethod TextDocumentDefinition - STextDocumentTypeDefinition :: SMethod TextDocumentTypeDefinition - STextDocumentImplementation :: SMethod TextDocumentImplementation - STextDocumentReferences :: SMethod TextDocumentReferences - STextDocumentDocumentHighlight :: SMethod TextDocumentDocumentHighlight - STextDocumentDocumentSymbol :: SMethod TextDocumentDocumentSymbol - STextDocumentCodeAction :: SMethod TextDocumentCodeAction - STextDocumentCodeLens :: SMethod TextDocumentCodeLens - SCodeLensResolve :: SMethod CodeLensResolve - STextDocumentDocumentLink :: SMethod TextDocumentDocumentLink - SDocumentLinkResolve :: SMethod DocumentLinkResolve - STextDocumentDocumentColor :: SMethod TextDocumentDocumentColor - STextDocumentColorPresentation :: SMethod TextDocumentColorPresentation - STextDocumentFormatting :: SMethod TextDocumentFormatting - STextDocumentRangeFormatting :: SMethod TextDocumentRangeFormatting - STextDocumentOnTypeFormatting :: SMethod TextDocumentOnTypeFormatting - STextDocumentRename :: SMethod TextDocumentRename - STextDocumentPrepareRename :: SMethod TextDocumentPrepareRename - STextDocumentFoldingRange :: SMethod TextDocumentFoldingRange - STextDocumentSelectionRange :: SMethod TextDocumentSelectionRange - STextDocumentPrepareCallHierarchy :: SMethod TextDocumentPrepareCallHierarchy - SCallHierarchyIncomingCalls :: SMethod CallHierarchyIncomingCalls - SCallHierarchyOutgoingCalls :: SMethod CallHierarchyOutgoingCalls - - STextDocumentSemanticTokens :: SMethod TextDocumentSemanticTokens - STextDocumentSemanticTokensFull :: SMethod TextDocumentSemanticTokensFull - STextDocumentSemanticTokensFullDelta :: SMethod TextDocumentSemanticTokensFullDelta - STextDocumentSemanticTokensRange :: SMethod TextDocumentSemanticTokensRange - SWorkspaceSemanticTokensRefresh :: SMethod WorkspaceSemanticTokensRefresh - - SWindowShowMessage :: SMethod WindowShowMessage - SWindowShowMessageRequest :: SMethod WindowShowMessageRequest - SWindowShowDocument :: SMethod WindowShowDocument - SWindowLogMessage :: SMethod WindowLogMessage - SWindowWorkDoneProgressCreate :: SMethod WindowWorkDoneProgressCreate - SWindowWorkDoneProgressCancel :: SMethod WindowWorkDoneProgressCancel - SProgress :: SMethod Progress - STelemetryEvent :: SMethod TelemetryEvent - SClientRegisterCapability :: SMethod ClientRegisterCapability - SClientUnregisterCapability :: SMethod ClientUnregisterCapability - SWorkspaceWorkspaceFolders :: SMethod WorkspaceWorkspaceFolders - SWorkspaceConfiguration :: SMethod WorkspaceConfiguration - SWorkspaceApplyEdit :: SMethod WorkspaceApplyEdit - STextDocumentPublishDiagnostics :: SMethod TextDocumentPublishDiagnostics - - SCancelRequest :: SMethod CancelRequest - SCustomMethod :: Text -> SMethod CustomMethod +import Unsafe.Coerce -- This instance is written manually rather than derived to avoid a dependency -- on 'dependent-sum-template'. @@ -198,9 +46,9 @@ instance GEq SMethod where -- This instance is written manually rather than derived to avoid a dependency -- on 'dependent-sum-template'. instance GCompare SMethod where - gcompare (SCustomMethod x) (SCustomMethod y) = case x `compare` y of + gcompare (SMethod_CustomMethod x) (SMethod_CustomMethod y) = case symbolVal x `compare` symbolVal y of LT -> GLT - EQ -> GEQ + EQ -> unsafeCoerce GEQ GT -> GGT -- This is much more compact than matching on every pair of constructors, which -- is what we would need to do for GHC to 'see' that this is correct. Nonetheless @@ -221,235 +69,79 @@ instance Ord (SMethod m) where deriving instance Show (SMethod m) --- Some useful type synonyms -type SClientMethod (m :: Method FromClient t) = SMethod m -type SServerMethod (m :: Method FromServer t) = SMethod m - -data SomeClientMethod = forall t (m :: Method FromClient t). SomeClientMethod (SMethod m) -data SomeServerMethod = forall t (m :: Method FromServer t). SomeServerMethod (SMethod m) +instance ToJSON (SMethod m) where + toJSON m = toJSON (SomeMethod m) -data SomeMethod where - SomeMethod :: forall m. SMethod m -> SomeMethod +------ deriving instance Show SomeMethod instance Eq SomeMethod where - (==) = (==) `on` toJSON + (==) = (==) `on` someMethodToMethodString instance Ord SomeMethod where - compare = compare `on` (getString . toJSON) - where - getString (A.String t) = t - getString _ = error "ToJSON instance for some method isn't string" -deriving instance Show SomeClientMethod -instance Eq SomeClientMethod where - (==) = (==) `on` toJSON -instance Ord SomeClientMethod where - compare = compare `on` (getString . toJSON) - where - getString (A.String t) = t - getString _ = error "ToJSON instance for some method isn't string" -deriving instance Show SomeServerMethod -instance Eq SomeServerMethod where - (==) = (==) `on` toJSON -instance Ord SomeServerMethod where - compare = compare `on` (getString . toJSON) - where - getString (A.String t) = t - getString _ = error "ToJSON instance for some method isn't string" + compare = compare `on` someMethodToMethodString --- --------------------------------------------------------------------- --- From JSON --- --------------------------------------------------------------------- +instance ToJSON SomeMethod where + toJSON sm = toJSON $ someMethodToMethodString sm instance FromJSON SomeMethod where - parseJSON v = client <|> server - where - client = do - c <- parseJSON v - case c of - -- Don't parse the client custom method so that we can still - -- parse the server methods - SomeClientMethod (SCustomMethod _) -> mempty - SomeClientMethod m -> pure $ SomeMethod m - server = do - c <- parseJSON v - case c of - SomeServerMethod m -> pure $ SomeMethod m + parseJSON v = do + s <- parseJSON v + pure $ methodStringToSomeMethod s -instance FromJSON SomeClientMethod where - -- General - parseJSON (A.String "initialize") = pure $ SomeClientMethod SInitialize - parseJSON (A.String "initialized") = pure $ SomeClientMethod SInitialized - parseJSON (A.String "shutdown") = pure $ SomeClientMethod SShutdown - parseJSON (A.String "exit") = pure $ SomeClientMethod SExit - -- Workspace - parseJSON (A.String "workspace/didChangeWorkspaceFolders") = pure $ SomeClientMethod SWorkspaceDidChangeWorkspaceFolders - parseJSON (A.String "workspace/didChangeConfiguration") = pure $ SomeClientMethod SWorkspaceDidChangeConfiguration - parseJSON (A.String "workspace/didChangeWatchedFiles") = pure $ SomeClientMethod SWorkspaceDidChangeWatchedFiles - parseJSON (A.String "workspace/symbol") = pure $ SomeClientMethod SWorkspaceSymbol - parseJSON (A.String "workspace/executeCommand") = pure $ SomeClientMethod SWorkspaceExecuteCommand - -- Document - parseJSON (A.String "textDocument/didOpen") = pure $ SomeClientMethod STextDocumentDidOpen - parseJSON (A.String "textDocument/didChange") = pure $ SomeClientMethod STextDocumentDidChange - parseJSON (A.String "textDocument/willSave") = pure $ SomeClientMethod STextDocumentWillSave - parseJSON (A.String "textDocument/willSaveWaitUntil") = pure $ SomeClientMethod STextDocumentWillSaveWaitUntil - parseJSON (A.String "textDocument/didSave") = pure $ SomeClientMethod STextDocumentDidSave - parseJSON (A.String "textDocument/didClose") = pure $ SomeClientMethod STextDocumentDidClose - parseJSON (A.String "textDocument/completion") = pure $ SomeClientMethod STextDocumentCompletion - parseJSON (A.String "completionItem/resolve") = pure $ SomeClientMethod SCompletionItemResolve - parseJSON (A.String "textDocument/hover") = pure $ SomeClientMethod STextDocumentHover - parseJSON (A.String "textDocument/signatureHelp") = pure $ SomeClientMethod STextDocumentSignatureHelp - parseJSON (A.String "textDocument/declaration") = pure $ SomeClientMethod STextDocumentDeclaration - parseJSON (A.String "textDocument/definition") = pure $ SomeClientMethod STextDocumentDefinition - parseJSON (A.String "textDocument/typeDefinition") = pure $ SomeClientMethod STextDocumentTypeDefinition - parseJSON (A.String "textDocument/implementation") = pure $ SomeClientMethod STextDocumentImplementation - parseJSON (A.String "textDocument/references") = pure $ SomeClientMethod STextDocumentReferences - parseJSON (A.String "textDocument/documentHighlight") = pure $ SomeClientMethod STextDocumentDocumentHighlight - parseJSON (A.String "textDocument/documentSymbol") = pure $ SomeClientMethod STextDocumentDocumentSymbol - parseJSON (A.String "textDocument/codeAction") = pure $ SomeClientMethod STextDocumentCodeAction - parseJSON (A.String "textDocument/codeLens") = pure $ SomeClientMethod STextDocumentCodeLens - parseJSON (A.String "codeLens/resolve") = pure $ SomeClientMethod SCodeLensResolve - parseJSON (A.String "textDocument/documentLink") = pure $ SomeClientMethod STextDocumentDocumentLink - parseJSON (A.String "documentLink/resolve") = pure $ SomeClientMethod SDocumentLinkResolve - parseJSON (A.String "textDocument/documentColor") = pure $ SomeClientMethod STextDocumentDocumentColor - parseJSON (A.String "textDocument/colorPresentation") = pure $ SomeClientMethod STextDocumentColorPresentation - parseJSON (A.String "textDocument/formatting") = pure $ SomeClientMethod STextDocumentFormatting - parseJSON (A.String "textDocument/rangeFormatting") = pure $ SomeClientMethod STextDocumentRangeFormatting - parseJSON (A.String "textDocument/onTypeFormatting") = pure $ SomeClientMethod STextDocumentOnTypeFormatting - parseJSON (A.String "textDocument/rename") = pure $ SomeClientMethod STextDocumentRename - parseJSON (A.String "textDocument/prepareRename") = pure $ SomeClientMethod STextDocumentPrepareRename - parseJSON (A.String "textDocument/foldingRange") = pure $ SomeClientMethod STextDocumentFoldingRange - parseJSON (A.String "textDocument/selectionRange") = pure $ SomeClientMethod STextDocumentSelectionRange - parseJSON (A.String "textDocument/prepareCallHierarchy") = pure $ SomeClientMethod STextDocumentPrepareCallHierarchy - parseJSON (A.String "callHierarchy/incomingCalls") = pure $ SomeClientMethod SCallHierarchyIncomingCalls - parseJSON (A.String "callHierarchy/outgoingCalls") = pure $ SomeClientMethod SCallHierarchyOutgoingCalls - parseJSON (A.String "textDocument/semanticTokens") = pure $ SomeClientMethod STextDocumentSemanticTokens - parseJSON (A.String "textDocument/semanticTokens/full") = pure $ SomeClientMethod STextDocumentSemanticTokensFull - parseJSON (A.String "textDocument/semanticTokens/full/delta") = pure $ SomeClientMethod STextDocumentSemanticTokensFullDelta - parseJSON (A.String "textDocument/semanticTokens/range") = pure $ SomeClientMethod STextDocumentSemanticTokensRange - parseJSON (A.String "window/workDoneProgress/cancel") = pure $ SomeClientMethod SWindowWorkDoneProgressCancel --- Cancelling - parseJSON (A.String "$/cancelRequest") = pure $ SomeClientMethod SCancelRequest --- Custom - parseJSON (A.String m) = pure $ SomeClientMethod (SCustomMethod m) - parseJSON _ = fail "SomeClientMethod" +------- -instance A.FromJSON SomeServerMethod where --- Server - -- Window - parseJSON (A.String "window/showMessage") = pure $ SomeServerMethod SWindowShowMessage - parseJSON (A.String "window/showMessageRequest") = pure $ SomeServerMethod SWindowShowMessageRequest - parseJSON (A.String "window/showDocument") = pure $ SomeServerMethod SWindowShowDocument - parseJSON (A.String "window/logMessage") = pure $ SomeServerMethod SWindowLogMessage - parseJSON (A.String "window/workDoneProgress/create") = pure $ SomeServerMethod SWindowWorkDoneProgressCreate - parseJSON (A.String "$/progress") = pure $ SomeServerMethod SProgress - parseJSON (A.String "telemetry/event") = pure $ SomeServerMethod STelemetryEvent - -- Client - parseJSON (A.String "client/registerCapability") = pure $ SomeServerMethod SClientRegisterCapability - parseJSON (A.String "client/unregisterCapability") = pure $ SomeServerMethod SClientUnregisterCapability - -- Workspace - parseJSON (A.String "workspace/workspaceFolders") = pure $ SomeServerMethod SWorkspaceWorkspaceFolders - parseJSON (A.String "workspace/configuration") = pure $ SomeServerMethod SWorkspaceConfiguration - parseJSON (A.String "workspace/applyEdit") = pure $ SomeServerMethod SWorkspaceApplyEdit - parseJSON (A.String "workspace/semanticTokens/refresh") = pure $ SomeServerMethod SWorkspaceSemanticTokensRefresh - -- Document - parseJSON (A.String "textDocument/publishDiagnostics") = pure $ SomeServerMethod STextDocumentPublishDiagnostics +-- Some useful type synonyms +type SClientMethod (m :: Method ClientToServer t) = SMethod m +type SServerMethod (m :: Method ServerToClient t) = SMethod m --- Cancelling - parseJSON (A.String "$/cancelRequest") = pure $ SomeServerMethod SCancelRequest +data SomeClientMethod = forall t (m :: Method ClientToServer t). SomeClientMethod (SMethod m) +deriving instance Show SomeClientMethod --- Custom - parseJSON (A.String m) = pure $ SomeServerMethod (SCustomMethod m) - parseJSON _ = fail "SomeServerMethod" +data SomeServerMethod = forall t (m :: Method ServerToClient t). SomeServerMethod (SMethod m) +deriving instance Show SomeServerMethod --- instance FromJSON (SMethod m) +someClientMethod :: SMethod m -> Maybe SomeClientMethod +someClientMethod s = case messageDirection s of + SClientToServer -> Just $ SomeClientMethod s + SServerToClient -> Nothing + SBothDirections -> Nothing --- --------------------------------------------------------------------- --- TO JSON --- --------------------------------------------------------------------- +someServerMethod :: SMethod m -> Maybe SomeServerMethod +someServerMethod s = case messageDirection s of + SServerToClient-> Just $ SomeServerMethod s + SClientToServer -> Nothing + SBothDirections -> Nothing -instance ToJSON SomeMethod where - toJSON (SomeMethod m) = toJSON m +instance FromJSON SomeClientMethod where + parseJSON v = do + (SomeMethod sm) <- parseJSON v + case someClientMethod sm of + Just scm -> pure scm + Nothing -> mempty instance ToJSON SomeClientMethod where - toJSON (SomeClientMethod m) = toJSON m -instance ToJSON SomeServerMethod where - toJSON (SomeServerMethod m) = toJSON m + toJSON (SomeClientMethod sm) = toJSON $ someMethodToMethodString $ SomeMethod sm -instance A.ToJSON (SMethod m) where --- Client - -- General - toJSON SInitialize = A.String "initialize" - toJSON SInitialized = A.String "initialized" - toJSON SShutdown = A.String "shutdown" - toJSON SExit = A.String "exit" - -- Workspace - toJSON SWorkspaceDidChangeWorkspaceFolders = A.String "workspace/didChangeWorkspaceFolders" - toJSON SWorkspaceDidChangeConfiguration = A.String "workspace/didChangeConfiguration" - toJSON SWorkspaceDidChangeWatchedFiles = A.String "workspace/didChangeWatchedFiles" - toJSON SWorkspaceSymbol = A.String "workspace/symbol" - toJSON SWorkspaceExecuteCommand = A.String "workspace/executeCommand" - -- Document - toJSON STextDocumentDidOpen = A.String "textDocument/didOpen" - toJSON STextDocumentDidChange = A.String "textDocument/didChange" - toJSON STextDocumentWillSave = A.String "textDocument/willSave" - toJSON STextDocumentWillSaveWaitUntil = A.String "textDocument/willSaveWaitUntil" - toJSON STextDocumentDidSave = A.String "textDocument/didSave" - toJSON STextDocumentDidClose = A.String "textDocument/didClose" - toJSON STextDocumentCompletion = A.String "textDocument/completion" - toJSON SCompletionItemResolve = A.String "completionItem/resolve" - toJSON STextDocumentHover = A.String "textDocument/hover" - toJSON STextDocumentSignatureHelp = A.String "textDocument/signatureHelp" - toJSON STextDocumentReferences = A.String "textDocument/references" - toJSON STextDocumentDocumentHighlight = A.String "textDocument/documentHighlight" - toJSON STextDocumentDocumentSymbol = A.String "textDocument/documentSymbol" - toJSON STextDocumentDeclaration = A.String "textDocument/declaration" - toJSON STextDocumentDefinition = A.String "textDocument/definition" - toJSON STextDocumentTypeDefinition = A.String "textDocument/typeDefinition" - toJSON STextDocumentImplementation = A.String "textDocument/implementation" - toJSON STextDocumentCodeAction = A.String "textDocument/codeAction" - toJSON STextDocumentCodeLens = A.String "textDocument/codeLens" - toJSON SCodeLensResolve = A.String "codeLens/resolve" - toJSON STextDocumentDocumentColor = A.String "textDocument/documentColor" - toJSON STextDocumentColorPresentation = A.String "textDocument/colorPresentation" - toJSON STextDocumentFormatting = A.String "textDocument/formatting" - toJSON STextDocumentRangeFormatting = A.String "textDocument/rangeFormatting" - toJSON STextDocumentOnTypeFormatting = A.String "textDocument/onTypeFormatting" - toJSON STextDocumentRename = A.String "textDocument/rename" - toJSON STextDocumentPrepareRename = A.String "textDocument/prepareRename" - toJSON STextDocumentFoldingRange = A.String "textDocument/foldingRange" - toJSON STextDocumentSelectionRange = A.String "textDocument/selectionRange" - toJSON STextDocumentPrepareCallHierarchy = A.String "textDocument/prepareCallHierarchy" - toJSON SCallHierarchyIncomingCalls = A.String "callHierarchy/incomingCalls" - toJSON SCallHierarchyOutgoingCalls = A.String "callHierarchy/outgoingCalls" - toJSON STextDocumentSemanticTokens = A.String "textDocument/semanticTokens" - toJSON STextDocumentSemanticTokensFull = A.String "textDocument/semanticTokens/full" - toJSON STextDocumentSemanticTokensFullDelta = A.String "textDocument/semanticTokens/full/delta" - toJSON STextDocumentSemanticTokensRange = A.String "textDocument/semanticTokens/range" - toJSON STextDocumentDocumentLink = A.String "textDocument/documentLink" - toJSON SDocumentLinkResolve = A.String "documentLink/resolve" - toJSON SWindowWorkDoneProgressCancel = A.String "window/workDoneProgress/cancel" --- Server - -- Window - toJSON SWindowShowMessage = A.String "window/showMessage" - toJSON SWindowShowMessageRequest = A.String "window/showMessageRequest" - toJSON SWindowShowDocument = A.String "window/showDocument" - toJSON SWindowLogMessage = A.String "window/logMessage" - toJSON SWindowWorkDoneProgressCreate = A.String "window/workDoneProgress/create" - toJSON SProgress = A.String "$/progress" - toJSON STelemetryEvent = A.String "telemetry/event" - -- Client - toJSON SClientRegisterCapability = A.String "client/registerCapability" - toJSON SClientUnregisterCapability = A.String "client/unregisterCapability" - -- Workspace - toJSON SWorkspaceWorkspaceFolders = A.String "workspace/workspaceFolders" - toJSON SWorkspaceConfiguration = A.String "workspace/configuration" - toJSON SWorkspaceApplyEdit = A.String "workspace/applyEdit" - toJSON SWorkspaceSemanticTokensRefresh = A.String "workspace/semanticTokens/refresh" - -- Document - toJSON STextDocumentPublishDiagnostics = A.String "textDocument/publishDiagnostics" - -- Cancelling - toJSON SCancelRequest = A.String "$/cancelRequest" --- Custom - toJSON (SCustomMethod m) = A.String m +instance FromJSON SomeServerMethod where + parseJSON v = do + (SomeMethod sm) <- parseJSON v + case someServerMethod sm of + Just scm -> pure scm + Nothing -> mempty -makeSingletonFromJSON 'SomeMethod ''SMethod +instance ToJSON SomeServerMethod where + toJSON (SomeServerMethod sm) = toJSON $ someMethodToMethodString $ SomeMethod sm + +instance KnownSymbol s => FromJSON (SMethod ('Method_CustomMethod s :: Method f t)) where + parseJSON v = do + sm <- parseJSON v + case sm of + SomeMethod (SMethod_CustomMethod x) -> case sameSymbol x (Proxy :: Proxy s) of + Just Refl -> pure $ SMethod_CustomMethod x + Nothing -> mempty + _ -> mempty + +-- TODO: generate these with everything else? +-- Generates lots of instances like this in terms of the FromJSON SomeMethod instance +-- instance FromJSON (SMethod Method_X) +makeSingletonFromJSON 'SomeMethod ''SMethod ['SMethod_CustomMethod] diff --git a/lsp-types/src/Language/LSP/Types/Parsing.hs b/lsp-types/src/Language/LSP/Types/Parsing.hs index 67316bc8c..1b5e7dbb7 100644 --- a/lsp-types/src/Language/LSP/Types/Parsing.hs +++ b/lsp-types/src/Language/LSP/Types/Parsing.hs @@ -1,40 +1,44 @@ -{-# LANGUAGE GADTs #-} -{-# LANGUAGE TypeOperators #-} -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE ConstraintKinds #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE TupleSections #-} -{-# LANGUAGE TypeApplications #-} -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} -{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TupleSections #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeInType #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE UndecidableInstances #-} module Language.LSP.Types.Parsing where +import Language.LSP.Types.Common +import Language.LSP.Types.Internal.Generated import Language.LSP.Types.LspId -import Language.LSP.Types.Method import Language.LSP.Types.Message +import Language.LSP.Types.Method -import Data.Aeson -import Data.Aeson.Types -import Data.GADT.Compare -import Data.Type.Equality -import Data.Function (on) +import Data.Aeson +import Data.Aeson.Types +import Data.Function (on) +import Data.GADT.Compare +import Data.Proxy +import Data.Type.Equality +import GHC.TypeLits (sameSymbol) -- --------------------------------------------------------------------- -- Working with arbitrary messages -- --------------------------------------------------------------------- data FromServerMessage' a where - FromServerMess :: forall t (m :: Method FromServer t) a. SMethod m -> Message m -> FromServerMessage' a - FromServerRsp :: forall (m :: Method FromClient Request) a. a m -> ResponseMessage m -> FromServerMessage' a + FromServerMess :: forall t (m :: Method ServerToClient t) a. SMethod m -> TMessage m -> FromServerMessage' a + FromServerRsp :: forall (m :: Method ClientToServer Request) a. a m -> TResponseMessage m -> FromServerMessage' a type FromServerMessage = FromServerMessage' SMethod @@ -45,33 +49,33 @@ instance Show FromServerMessage where instance ToJSON FromServerMessage where toJSON (FromServerMess m p) = serverMethodJSON m (toJSON p) - toJSON (FromServerRsp m p) = clientResponseJSON m (toJSON p) + toJSON (FromServerRsp m p) = clientResponseJSON m (toJSON p) -fromServerNot :: forall (m :: Method FromServer Notification). - Message m ~ NotificationMessage m => NotificationMessage m -> FromServerMessage -fromServerNot m@NotificationMessage{_method=meth} = FromServerMess meth m +fromServerNot :: forall (m :: Method ServerToClient Notification). + TMessage m ~ TNotificationMessage m => TNotificationMessage m -> FromServerMessage +fromServerNot m@TNotificationMessage{_method=meth} = FromServerMess meth m -fromServerReq :: forall (m :: Method FromServer Request). - Message m ~ RequestMessage m => RequestMessage m -> FromServerMessage -fromServerReq m@RequestMessage{_method=meth} = FromServerMess meth m +fromServerReq :: forall (m :: Method ServerToClient Request). + TMessage m ~ TRequestMessage m => TRequestMessage m -> FromServerMessage +fromServerReq m@TRequestMessage{_method=meth} = FromServerMess meth m data FromClientMessage' a where - FromClientMess :: forall t (m :: Method FromClient t) a. SMethod m -> Message m -> FromClientMessage' a - FromClientRsp :: forall (m :: Method FromServer Request) a. a m -> ResponseMessage m -> FromClientMessage' a + FromClientMess :: forall t (m :: Method ClientToServer t) a . SMethod m -> TMessage m -> FromClientMessage' a + FromClientRsp :: forall (m :: Method ServerToClient Request) a . a m -> TResponseMessage m -> FromClientMessage' a type FromClientMessage = FromClientMessage' SMethod instance ToJSON FromClientMessage where toJSON (FromClientMess m p) = clientMethodJSON m (toJSON p) - toJSON (FromClientRsp m p) = serverResponseJSON m (toJSON p) + toJSON (FromClientRsp m p) = serverResponseJSON m (toJSON p) -fromClientNot :: forall (m :: Method FromClient Notification). - Message m ~ NotificationMessage m => NotificationMessage m -> FromClientMessage -fromClientNot m@NotificationMessage{_method=meth} = FromClientMess meth m +fromClientNot :: forall (m :: Method ClientToServer Notification). + TMessage m ~ TNotificationMessage m => TNotificationMessage m -> FromClientMessage +fromClientNot m@TNotificationMessage{_method=meth} = FromClientMess meth m -fromClientReq :: forall (m :: Method FromClient Request). - Message m ~ RequestMessage m => RequestMessage m -> FromClientMessage -fromClientReq m@RequestMessage{_method=meth} = FromClientMess meth m +fromClientReq :: forall (m :: Method ClientToServer Request). + TMessage m ~ TRequestMessage m => TRequestMessage m -> FromClientMessage +fromClientReq m@TRequestMessage{_method=meth} = FromClientMess meth m -- --------------------------------------------------------------------- -- Parsing @@ -88,7 +92,7 @@ Notification | jsonrpc | | method | params? -} {-# INLINE parseServerMessage #-} -parseServerMessage :: LookupFunc FromClient a -> Value -> Parser (FromServerMessage' a) +parseServerMessage :: LookupFunc ClientToServer a -> Value -> Parser (FromServerMessage' a) parseServerMessage lookupId v@(Object o) = do methMaybe <- o .:! "method" idMaybe <- o .:! "id" @@ -98,14 +102,14 @@ parseServerMessage lookupId v@(Object o) = do case splitServerMethod m of IsServerNot -> FromServerMess m <$> parseJSON v IsServerReq -> FromServerMess m <$> parseJSON v - IsServerEither | SCustomMethod cm <- m -> do + IsServerEither | SMethod_CustomMethod (p :: Proxy s') <- m -> do case idMaybe of -- Request Just _ -> - let m' = (SCustomMethod cm :: SMethod (CustomMethod :: Method FromServer Request)) + let m' = (SMethod_CustomMethod p :: SMethod (Method_CustomMethod s' :: Method ServerToClient Request)) in FromServerMess m' <$> parseJSON v Nothing -> - let m' = (SCustomMethod cm :: SMethod (CustomMethod :: Method FromServer Notification)) + let m' = (SMethod_CustomMethod p :: SMethod (Method_CustomMethod s' :: Method ServerToClient Notification)) in FromServerMess m' <$> parseJSON v Nothing -> do case idMaybe of @@ -117,7 +121,7 @@ parseServerMessage lookupId v@(Object o) = do parseServerMessage _ v = fail $ unwords ["parseServerMessage expected object, got:",show v] {-# INLINE parseClientMessage #-} -parseClientMessage :: LookupFunc FromServer a -> Value -> Parser (FromClientMessage' a) +parseClientMessage :: LookupFunc ServerToClient a -> Value -> Parser (FromClientMessage' a) parseClientMessage lookupId v@(Object o) = do methMaybe <- o .:! "method" idMaybe <- o .:! "id" @@ -127,14 +131,14 @@ parseClientMessage lookupId v@(Object o) = do case splitClientMethod m of IsClientNot -> FromClientMess m <$> parseJSON v IsClientReq -> FromClientMess m <$> parseJSON v - IsClientEither | SCustomMethod cm <- m -> do + IsClientEither | SMethod_CustomMethod (p :: Proxy s') <- m -> do case idMaybe of -- Request Just _ -> - let m' = (SCustomMethod cm :: SMethod (CustomMethod :: Method FromClient Request)) + let m' = (SMethod_CustomMethod p :: SMethod (Method_CustomMethod s' :: Method ClientToServer Request)) in FromClientMess m' <$> parseJSON v Nothing -> - let m' = (SCustomMethod cm :: SMethod (CustomMethod :: Method FromClient Notification)) + let m' = (SMethod_CustomMethod p :: SMethod (Method_CustomMethod s' :: Method ClientToServer Notification)) in FromClientMess m' <$> parseJSON v Nothing -> do case idMaybe of @@ -150,147 +154,171 @@ parseClientMessage _ v = fail $ unwords ["parseClientMessage expected object, go -- --------------------------------------------------------------------- {-# INLINE clientResponseJSON #-} -clientResponseJSON :: SClientMethod m -> (HasJSON (ResponseMessage m) => x) -> x +clientResponseJSON :: SClientMethod m -> (HasJSON (TResponseMessage m) => x) -> x clientResponseJSON m x = case splitClientMethod m of - IsClientReq -> x + IsClientReq -> x IsClientEither -> x {-# INLINE serverResponseJSON #-} -serverResponseJSON :: SServerMethod m -> (HasJSON (ResponseMessage m) => x) -> x +serverResponseJSON :: SServerMethod m -> (HasJSON (TResponseMessage m) => x) -> x serverResponseJSON m x = case splitServerMethod m of - IsServerReq -> x + IsServerReq -> x IsServerEither -> x {-# INLINE clientMethodJSON#-} -clientMethodJSON :: SClientMethod m -> (ToJSON (ClientMessage m) => x) -> x +clientMethodJSON :: SClientMethod m -> (ToJSON (TClientMessage m) => x) -> x clientMethodJSON m x = case splitClientMethod m of - IsClientNot -> x - IsClientReq -> x + IsClientNot -> x + IsClientReq -> x IsClientEither -> x {-# INLINE serverMethodJSON #-} -serverMethodJSON :: SServerMethod m -> (ToJSON (ServerMessage m) => x) -> x +serverMethodJSON :: SServerMethod m -> (ToJSON (TServerMessage m) => x) -> x serverMethodJSON m x = case splitServerMethod m of - IsServerNot -> x - IsServerReq -> x + IsServerNot -> x + IsServerReq -> x IsServerEither -> x type HasJSON a = (ToJSON a,FromJSON a,Eq a) -- Reify universal properties about Client/Server Messages -data ClientNotOrReq (m :: Method FromClient t) where +data ClientNotOrReq (m :: Method ClientToServer t) where IsClientNot - :: ( HasJSON (ClientMessage m) - , Message m ~ NotificationMessage m) - => ClientNotOrReq (m :: Method FromClient Notification) + :: ( HasJSON (TClientMessage m) + , TMessage m ~ TNotificationMessage m) + => ClientNotOrReq (m :: Method ClientToServer Notification) IsClientReq - :: forall (m :: Method FromClient Request). - ( HasJSON (ClientMessage m) - , HasJSON (ResponseMessage m) - , Message m ~ RequestMessage m) + :: forall (m :: Method ClientToServer Request). + ( HasJSON (TClientMessage m) + , HasJSON (TResponseMessage m) + , TMessage m ~ TRequestMessage m) => ClientNotOrReq m IsClientEither - :: ClientNotOrReq CustomMethod + :: ClientNotOrReq (Method_CustomMethod s) -data ServerNotOrReq (m :: Method FromServer t) where +data ServerNotOrReq (m :: Method ServerToClient t) where IsServerNot - :: ( HasJSON (ServerMessage m) - , Message m ~ NotificationMessage m) - => ServerNotOrReq (m :: Method FromServer Notification) + :: ( HasJSON (TServerMessage m) + , TMessage m ~ TNotificationMessage m) + => ServerNotOrReq (m :: Method ServerToClient Notification) IsServerReq - :: forall (m :: Method FromServer Request). - ( HasJSON (ServerMessage m) - , HasJSON (ResponseMessage m) - , Message m ~ RequestMessage m) + :: forall (m :: Method ServerToClient Request). + ( HasJSON (TServerMessage m) + , HasJSON (TResponseMessage m) + , TMessage m ~ TRequestMessage m) => ServerNotOrReq m IsServerEither - :: ServerNotOrReq CustomMethod + :: ServerNotOrReq (Method_CustomMethod s) {-# INLINE splitClientMethod #-} splitClientMethod :: SClientMethod m -> ClientNotOrReq m -splitClientMethod SInitialize = IsClientReq -splitClientMethod SInitialized = IsClientNot -splitClientMethod SShutdown = IsClientReq -splitClientMethod SExit = IsClientNot -splitClientMethod SWorkspaceDidChangeWorkspaceFolders = IsClientNot -splitClientMethod SWorkspaceDidChangeConfiguration = IsClientNot -splitClientMethod SWorkspaceDidChangeWatchedFiles = IsClientNot -splitClientMethod SWorkspaceSymbol = IsClientReq -splitClientMethod SWorkspaceExecuteCommand = IsClientReq -splitClientMethod SWindowWorkDoneProgressCancel = IsClientNot -splitClientMethod STextDocumentDidOpen = IsClientNot -splitClientMethod STextDocumentDidChange = IsClientNot -splitClientMethod STextDocumentWillSave = IsClientNot -splitClientMethod STextDocumentWillSaveWaitUntil = IsClientReq -splitClientMethod STextDocumentDidSave = IsClientNot -splitClientMethod STextDocumentDidClose = IsClientNot -splitClientMethod STextDocumentCompletion = IsClientReq -splitClientMethod SCompletionItemResolve = IsClientReq -splitClientMethod STextDocumentHover = IsClientReq -splitClientMethod STextDocumentSignatureHelp = IsClientReq -splitClientMethod STextDocumentDeclaration = IsClientReq -splitClientMethod STextDocumentDefinition = IsClientReq -splitClientMethod STextDocumentTypeDefinition = IsClientReq -splitClientMethod STextDocumentImplementation = IsClientReq -splitClientMethod STextDocumentReferences = IsClientReq -splitClientMethod STextDocumentDocumentHighlight = IsClientReq -splitClientMethod STextDocumentDocumentSymbol = IsClientReq -splitClientMethod STextDocumentCodeAction = IsClientReq -splitClientMethod STextDocumentCodeLens = IsClientReq -splitClientMethod SCodeLensResolve = IsClientReq -splitClientMethod STextDocumentDocumentLink = IsClientReq -splitClientMethod SDocumentLinkResolve = IsClientReq -splitClientMethod STextDocumentDocumentColor = IsClientReq -splitClientMethod STextDocumentColorPresentation = IsClientReq -splitClientMethod STextDocumentFormatting = IsClientReq -splitClientMethod STextDocumentRangeFormatting = IsClientReq -splitClientMethod STextDocumentOnTypeFormatting = IsClientReq -splitClientMethod STextDocumentRename = IsClientReq -splitClientMethod STextDocumentPrepareRename = IsClientReq -splitClientMethod STextDocumentFoldingRange = IsClientReq -splitClientMethod STextDocumentSelectionRange = IsClientReq -splitClientMethod STextDocumentPrepareCallHierarchy = IsClientReq -splitClientMethod SCallHierarchyIncomingCalls = IsClientReq -splitClientMethod SCallHierarchyOutgoingCalls = IsClientReq -splitClientMethod STextDocumentSemanticTokens = IsClientReq -splitClientMethod STextDocumentSemanticTokensFull = IsClientReq -splitClientMethod STextDocumentSemanticTokensFullDelta = IsClientReq -splitClientMethod STextDocumentSemanticTokensRange = IsClientReq -splitClientMethod SCancelRequest = IsClientNot -splitClientMethod SCustomMethod{} = IsClientEither +splitClientMethod = \case + SMethod_Initialize -> IsClientReq + SMethod_Initialized -> IsClientNot + SMethod_Shutdown -> IsClientReq + SMethod_Exit -> IsClientNot + SMethod_WorkspaceDidChangeWorkspaceFolders -> IsClientNot + SMethod_WorkspaceDidChangeConfiguration -> IsClientNot + SMethod_WorkspaceDidChangeWatchedFiles -> IsClientNot + SMethod_WorkspaceSymbol -> IsClientReq + SMethod_WorkspaceExecuteCommand -> IsClientReq + SMethod_WindowWorkDoneProgressCancel -> IsClientNot + SMethod_TextDocumentDidOpen -> IsClientNot + SMethod_TextDocumentDidChange -> IsClientNot + SMethod_TextDocumentWillSave -> IsClientNot + SMethod_TextDocumentWillSaveWaitUntil -> IsClientReq + SMethod_TextDocumentDidSave -> IsClientNot + SMethod_TextDocumentDidClose -> IsClientNot + SMethod_TextDocumentCompletion -> IsClientReq + SMethod_TextDocumentHover -> IsClientReq + SMethod_TextDocumentSignatureHelp -> IsClientReq + SMethod_TextDocumentDeclaration -> IsClientReq + SMethod_TextDocumentDefinition -> IsClientReq + SMethod_TextDocumentTypeDefinition -> IsClientReq + SMethod_TextDocumentImplementation -> IsClientReq + SMethod_TextDocumentReferences -> IsClientReq + SMethod_TextDocumentDocumentHighlight -> IsClientReq + SMethod_TextDocumentDocumentSymbol -> IsClientReq + SMethod_TextDocumentCodeAction -> IsClientReq + SMethod_TextDocumentCodeLens -> IsClientReq + SMethod_TextDocumentDocumentLink -> IsClientReq + SMethod_TextDocumentDocumentColor -> IsClientReq + SMethod_TextDocumentColorPresentation -> IsClientReq + SMethod_TextDocumentFormatting -> IsClientReq + SMethod_TextDocumentRangeFormatting -> IsClientReq + SMethod_TextDocumentOnTypeFormatting -> IsClientReq + SMethod_TextDocumentRename -> IsClientReq + SMethod_TextDocumentPrepareRename -> IsClientReq + SMethod_TextDocumentFoldingRange -> IsClientReq + SMethod_TextDocumentSelectionRange -> IsClientReq + SMethod_TextDocumentPrepareCallHierarchy -> IsClientReq + SMethod_TextDocumentLinkedEditingRange -> IsClientReq + SMethod_CallHierarchyIncomingCalls -> IsClientReq + SMethod_CallHierarchyOutgoingCalls -> IsClientReq + SMethod_TextDocumentSemanticTokensFull -> IsClientReq + SMethod_TextDocumentSemanticTokensFullDelta -> IsClientReq + SMethod_TextDocumentSemanticTokensRange -> IsClientReq + SMethod_WorkspaceSemanticTokensRefresh -> IsClientReq + SMethod_WorkspaceWillCreateFiles -> IsClientReq + SMethod_WorkspaceWillDeleteFiles -> IsClientReq + SMethod_WorkspaceWillRenameFiles -> IsClientReq + SMethod_WorkspaceDidCreateFiles -> IsClientNot + SMethod_WorkspaceDidDeleteFiles -> IsClientNot + SMethod_WorkspaceDidRenameFiles -> IsClientNot + SMethod_TextDocumentMoniker -> IsClientReq + SMethod_TextDocumentPrepareTypeHierarchy -> IsClientReq + SMethod_TypeHierarchySubtypes -> IsClientReq + SMethod_TypeHierarchySupertypes -> IsClientReq + SMethod_WorkspaceInlineValueRefresh -> IsClientReq + SMethod_TextDocumentInlineValue -> IsClientReq + SMethod_WorkspaceInlayHintRefresh -> IsClientReq + SMethod_TextDocumentInlayHint -> IsClientReq + SMethod_TextDocumentDiagnostic -> IsClientReq + SMethod_WorkspaceDiagnostic -> IsClientReq + SMethod_WorkspaceDiagnosticRefresh -> IsClientReq + SMethod_CodeLensResolve -> IsClientReq + SMethod_InlayHintResolve -> IsClientReq + SMethod_CodeActionResolve -> IsClientReq + SMethod_DocumentLinkResolve -> IsClientReq + SMethod_CompletionItemResolve -> IsClientReq + SMethod_WorkspaceSymbolResolve -> IsClientReq + SMethod_NotebookDocumentDidChange -> IsClientNot + SMethod_NotebookDocumentDidClose -> IsClientNot + SMethod_NotebookDocumentDidOpen -> IsClientNot + SMethod_NotebookDocumentDidSave -> IsClientNot + SMethod_SetTrace -> IsClientNot + SMethod_Progress -> IsClientNot + SMethod_CancelRequest -> IsClientNot + (SMethod_CustomMethod _) -> IsClientEither {-# INLINE splitServerMethod #-} splitServerMethod :: SServerMethod m -> ServerNotOrReq m --- Window -splitServerMethod SWindowShowMessage = IsServerNot -splitServerMethod SWindowShowMessageRequest = IsServerReq -splitServerMethod SWindowShowDocument = IsServerReq -splitServerMethod SWindowLogMessage = IsServerNot -splitServerMethod SWindowWorkDoneProgressCreate = IsServerReq -splitServerMethod SProgress = IsServerNot -splitServerMethod STelemetryEvent = IsServerNot --- Client -splitServerMethod SClientRegisterCapability = IsServerReq -splitServerMethod SClientUnregisterCapability = IsServerReq --- Workspace -splitServerMethod SWorkspaceWorkspaceFolders = IsServerReq -splitServerMethod SWorkspaceConfiguration = IsServerReq -splitServerMethod SWorkspaceApplyEdit = IsServerReq -splitServerMethod SWorkspaceSemanticTokensRefresh = IsServerReq --- Document -splitServerMethod STextDocumentPublishDiagnostics = IsServerNot --- Cancelling -splitServerMethod SCancelRequest = IsServerNot --- Custom -splitServerMethod SCustomMethod{} = IsServerEither +splitServerMethod = \case + SMethod_WindowShowMessage -> IsServerNot + SMethod_WindowShowMessageRequest -> IsServerReq + SMethod_WindowShowDocument -> IsServerReq + SMethod_WindowLogMessage -> IsServerNot + SMethod_WindowWorkDoneProgressCreate -> IsServerReq + SMethod_Progress -> IsServerNot + SMethod_TelemetryEvent -> IsServerNot + SMethod_ClientRegisterCapability -> IsServerReq + SMethod_ClientUnregisterCapability -> IsServerReq + SMethod_WorkspaceWorkspaceFolders -> IsServerReq + SMethod_WorkspaceConfiguration -> IsServerReq + SMethod_WorkspaceApplyEdit -> IsServerReq + SMethod_TextDocumentPublishDiagnostics -> IsServerNot + SMethod_LogTrace -> IsServerNot + SMethod_CancelRequest -> IsServerNot + SMethod_WorkspaceCodeLensRefresh -> IsServerReq + (SMethod_CustomMethod _) -> IsServerEither -- | Given a witness that two custom methods are of the same type, produce a witness that the methods are the same data CustomEq m1 m2 where CustomEq - :: (m1 ~ (CustomMethod :: Method f t1), m2 ~ (CustomMethod :: Method f t2)) + :: (m1 ~ (Method_CustomMethod s :: Method f t1), m2 ~ (Method_CustomMethod s :: Method f t2)) => { runCustomEq :: (t1 ~ t2 => m1 :~~: m2) } -> CustomEq m1 m2 @@ -316,10 +344,11 @@ mEqServer m1 m2 = go (splitServerMethod m1) (splitServerMethod m2) Refl <- geq m1 m2 pure $ Right HRefl go IsServerEither IsServerEither - | SCustomMethod c1 <- m1 - , SCustomMethod c2 <- m2 - , c1 == c2 - = Just $ Left $ CustomEq HRefl + | SMethod_CustomMethod p1 <- m1 + , SMethod_CustomMethod p2 <- m2 + = case sameSymbol p1 p2 of + Just Refl -> Just $ Left $ CustomEq HRefl + _ -> Nothing go _ _ = Nothing -- | Heterogeneous equality on singleton client methods @@ -333,8 +362,9 @@ mEqClient m1 m2 = go (splitClientMethod m1) (splitClientMethod m2) Refl <- geq m1 m2 pure $ Right HRefl go IsClientEither IsClientEither - | SCustomMethod c1 <- m1 - , SCustomMethod c2 <- m2 - , c1 == c2 - = Just $ Left $ CustomEq HRefl + | SMethod_CustomMethod p1 <- m1 + , SMethod_CustomMethod p2 <- m2 + = case sameSymbol p1 p2 of + Just Refl -> Just $ Left $ CustomEq HRefl + _ -> Nothing go _ _ = Nothing diff --git a/lsp-types/src/Language/LSP/Types/Progress.hs b/lsp-types/src/Language/LSP/Types/Progress.hs index e9929de31..af12255d6 100644 --- a/lsp-types/src/Language/LSP/Types/Progress.hs +++ b/lsp-types/src/Language/LSP/Types/Progress.hs @@ -1,214 +1,29 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE DeriveFunctor #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE OverloadedStrings #-} - -module Language.LSP.Types.Progress where - -import Control.Monad (unless) -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Maybe (catMaybes) -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.Utils - --- | A token used to report progress back or return partial results for a --- specific request. --- @since 0.17.0.0 -data ProgressToken - = ProgressNumericToken Int32 - | ProgressTextToken Text - deriving (Show, Read, Eq, Ord) - -deriveJSON lspOptionsUntagged ''ProgressToken - --- | Parameters for a $/progress notification. -data ProgressParams t = - ProgressParams { - _token :: ProgressToken - , _value :: t - } deriving (Show, Read, Eq, Functor) - -deriveJSON lspOptions ''ProgressParams - --- | Parameters for 'WorkDoneProgressBeginNotification'. --- --- @since 0.10.0.0 -data WorkDoneProgressBeginParams = - WorkDoneProgressBeginParams { - -- | Mandatory title of the progress operation. - -- Used to briefly inform about the kind of operation being - -- performed. Examples: "Indexing" or "Linking dependencies". - _title :: Text - -- | Controls if a cancel button should show to allow the user to cancel the - -- long running operation. Clients that don't support cancellation are allowed - -- to ignore the setting. - , _cancellable :: Maybe Bool - -- | Optional, more detailed associated progress - -- message. Contains complementary information to the - -- '_title'. Examples: "3/25 files", - -- "project/src/module2", "node_modules/some_dep". If - -- unset, the previous progress message (if any) is - -- still valid. - , _message :: Maybe Text - -- | Optional progress percentage to display (value 100 is considered 100%). - -- If not provided infinite progress is assumed and clients are allowed - -- to ignore the '_percentage' value in subsequent in report notifications. - -- - -- The value should be steadily rising. Clients are free to ignore values - -- that are not following this rule. - , _percentage :: Maybe UInt - } deriving (Show, Read, Eq) - -instance A.ToJSON WorkDoneProgressBeginParams where - toJSON WorkDoneProgressBeginParams{..} = - A.object $ catMaybes - [ Just $ "kind" A..= ("begin" :: Text) - , Just $ "title" A..= _title - , ("cancellable" A..=) <$> _cancellable - , ("message" A..=) <$> _message - , ("percentage" A..=) <$> _percentage - ] - -instance A.FromJSON WorkDoneProgressBeginParams where - parseJSON = A.withObject "WorkDoneProgressBegin" $ \o -> do - kind <- o A..: "kind" - unless (kind == ("begin" :: Text)) $ fail $ "Expected kind \"begin\" but got " ++ show kind - _title <- o A..: "title" - _cancellable <- o A..:? "cancellable" - _message <- o A..:? "message" - _percentage <- o A..:? "percentage" - pure WorkDoneProgressBeginParams{..} - --- The $/progress begin notification is sent from the server to the --- client to ask the client to start progress. --- --- @since 0.10.0.0 - --- | Parameters for 'WorkDoneProgressReportNotification' --- --- @since 0.10.0.0 -data WorkDoneProgressReportParams = - WorkDoneProgressReportParams { - _cancellable :: Maybe Bool - -- | Optional, more detailed associated progress - -- message. Contains complementary information to the - -- '_title'. Examples: "3/25 files", - -- "project/src/module2", "node_modules/some_dep". If - -- unset, the previous progress message (if any) is - -- still valid. - , _message :: Maybe Text - -- | Optional progress percentage to display (value 100 is considered 100%). - -- If infinite progress was indicated in the start notification client - -- are allowed to ignore the value. In addition the value should be steadily - -- rising. Clients are free to ignore values that are not following this rule. - , _percentage :: Maybe UInt - } deriving (Show, Read, Eq) - -instance A.ToJSON WorkDoneProgressReportParams where - toJSON WorkDoneProgressReportParams{..} = - A.object $ catMaybes - [ Just $ "kind" A..= ("report" :: Text) - , ("cancellable" A..=) <$> _cancellable - , ("message" A..=) <$> _message - , ("percentage" A..=) <$> _percentage - ] - -instance A.FromJSON WorkDoneProgressReportParams where - parseJSON = A.withObject "WorkDoneProgressReport" $ \o -> do - kind <- o A..: "kind" - unless (kind == ("report" :: Text)) $ fail $ "Expected kind \"report\" but got " ++ show kind - _cancellable <- o A..:? "cancellable" - _message <- o A..:? "message" - _percentage <- o A..:? "percentage" - pure WorkDoneProgressReportParams{..} - --- The workdone $/progress report notification is sent from the server to the --- client to report progress for a previously started progress. --- --- @since 0.10.0.0 - --- | Parameters for 'WorkDoneProgressEndNotification'. --- --- @since 0.10.0.0 -data WorkDoneProgressEndParams = - WorkDoneProgressEndParams { - _message :: Maybe Text - } deriving (Show, Read, Eq) - -instance A.ToJSON WorkDoneProgressEndParams where - toJSON WorkDoneProgressEndParams{..} = - A.object $ catMaybes - [ Just $ "kind" A..= ("end" :: Text) - , ("message" A..=) <$> _message - ] - -instance A.FromJSON WorkDoneProgressEndParams where - parseJSON = A.withObject "WorkDoneProgressEnd" $ \o -> do - kind <- o A..: "kind" - unless (kind == ("end" :: Text)) $ fail $ "Expected kind \"end\" but got " ++ show kind - _message <- o A..:? "message" - pure WorkDoneProgressEndParams{..} - --- The $/progress end notification is sent from the server to the --- client to stop a previously started progress. --- --- @since 0.10.0.0 - --- | Parameters for 'WorkDoneProgressCancelNotification'. --- --- @since 0.10.0.0 -data WorkDoneProgressCancelParams = - WorkDoneProgressCancelParams { - -- | A unique identifier to associate multiple progress - -- notifications with the same progress. - _token :: ProgressToken - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkDoneProgressCancelParams - --- The window/workDoneProgress/cancel notification is sent from the client to the server --- to inform the server that the user has pressed the cancel button on the progress UX. --- A server receiving a cancel request must still close a progress using the done notification. --- --- @since 0.10.0.0 - -data WorkDoneProgressCreateParams = - WorkDoneProgressCreateParams { - _token :: ProgressToken - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkDoneProgressCreateParams - -data WorkDoneProgressOptions = - WorkDoneProgressOptions - { _workDoneProgress :: Maybe Bool - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''WorkDoneProgressOptions - -data WorkDoneProgressParams = - WorkDoneProgressParams - { -- | An optional token that a server can use to report work done progress - _workDoneToken :: Maybe ProgressToken - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''WorkDoneProgressParams - -data SomeProgressParams - = Begin WorkDoneProgressBeginParams - | Report WorkDoneProgressReportParams - | End WorkDoneProgressEndParams - deriving Eq - -deriveJSON lspOptionsUntagged ''SomeProgressParams - -data PartialResultParams = - PartialResultParams - { -- | An optional token that a server can use to report partial results - -- (e.g. streaming) to the client. - _partialResultToken :: Maybe ProgressToken - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''PartialResultParams +module Language.LSP.Types.Progress + ( _workDoneProgressBegin + , _workDoneProgressEnd + , _workDoneProgressReport + ) + where + +import Control.Lens +import Data.Aeson + +import Language.LSP.Types.Internal.Generated + +-- From lens-aeson +_JSON :: (ToJSON a, FromJSON a) => Prism' Value a +_JSON = prism toJSON $ \x -> case fromJSON x of + Success y -> Right y; + _ -> Left x + +-- | Prism for extracting the 'WorkDoneProgressBegin' case from the unstructured 'value' field of 'ProgressParams'. +_workDoneProgressBegin :: Prism' Value WorkDoneProgressBegin +_workDoneProgressBegin = _JSON + +-- | Prism for extracting the 'WorkDoneProgressEnd' case from the unstructured 'value' field of 'ProgressParams'. +_workDoneProgressEnd :: Prism' Value WorkDoneProgressEnd +_workDoneProgressEnd = _JSON + +-- | Prism for extracting the 'WorkDoneProgressReport' case from the unstructured 'value' field of 'ProgressParams'. +_workDoneProgressReport :: Prism' Value WorkDoneProgressReport +_workDoneProgressReport = _JSON diff --git a/lsp-types/src/Language/LSP/Types/References.hs b/lsp-types/src/Language/LSP/Types/References.hs deleted file mode 100644 index 9700d674e..000000000 --- a/lsp-types/src/Language/LSP/Types/References.hs +++ /dev/null @@ -1,43 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} --- | Find References Request --- https://microsoft.github.io/language-server-protocol/specifications/specification-3-15/#textDocument_references -module Language.LSP.Types.References where - -import Data.Aeson.TH - -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Progress -import Language.LSP.Types.Utils - -data ReferencesClientCapabilities = - ReferencesClientCapabilities - { -- | Whether references supports dynamic registration. - _dynamicRegistration :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''ReferencesClientCapabilities - -makeExtendingDatatype "ReferenceOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''ReferenceOptions - -makeExtendingDatatype "ReferenceRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''ReferenceOptions - ] - [] -deriveJSON lspOptions ''ReferenceRegistrationOptions - -data ReferenceContext = - ReferenceContext - { -- | Include the declaration of the current symbol. - _includeDeclaration :: Bool - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''ReferenceContext - -makeExtendingDatatype "ReferenceParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_context", [t| ReferenceContext |])] -deriveJSON lspOptions ''ReferenceParams diff --git a/lsp-types/src/Language/LSP/Types/Registration.hs b/lsp-types/src/Language/LSP/Types/Registration.hs index 8f4ae558f..f302a885b 100644 --- a/lsp-types/src/Language/LSP/Types/Registration.hs +++ b/lsp-types/src/Language/LSP/Types/Registration.hs @@ -1,123 +1,56 @@ -{-# LANGUAGE GADTs #-} -{-# LANGUAGE TypeApplications #-} -{-# LANGUAGE TypeFamilyDependencies #-} +{-# LANGUAGE DeriveAnyClass #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE ExistentialQuantification #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE TypeOperators #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE StandaloneDeriving #-} -{-# LANGUAGE DeriveGeneric #-} -{-# LANGUAGE DeriveAnyClass #-} -{-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} -{-# OPTIONS_GHC -Werror=incomplete-patterns #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE TypeInType #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE UndecidableInstances #-} + +{-# OPTIONS_GHC -ddump-splices -ddump-to-file -dsuppress-uniques -dsuppress-coercions -dsuppress-type-applications -dsuppress-unfoldings -dsuppress-idinfo -dppr-cols=200 -dumpdir /tmp/dumps #-} module Language.LSP.Types.Registration where -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Data.Function (on) -import Data.Kind -import Data.Void (Void) -import GHC.Generics -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.Command import Language.LSP.Types.Common -import Language.LSP.Types.Completion -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation +import Language.LSP.Types.Internal.Generated +import Language.LSP.Types.Internal.Lenses import Language.LSP.Types.Method -import Language.LSP.Types.References -import Language.LSP.Types.Rename -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.SelectionRange -import Language.LSP.Types.SemanticTokens -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition import Language.LSP.Types.Utils -import Language.LSP.Types.WatchedFiles -import Language.LSP.Types.WorkspaceSymbol +import Control.Lens.TH +import Data.Aeson +import Data.Text (Text) +import qualified Data.Text as T +import GHC.Generics --- --------------------------------------------------------------------- - --- | Matches up the registration options for a specific method -type family RegistrationOptions (m :: Method FromClient t) :: Type where - -- Workspace - RegistrationOptions WorkspaceDidChangeWorkspaceFolders = Empty - RegistrationOptions WorkspaceDidChangeConfiguration = Empty - RegistrationOptions WorkspaceDidChangeWatchedFiles = DidChangeWatchedFilesRegistrationOptions - RegistrationOptions WorkspaceSymbol = WorkspaceSymbolRegistrationOptions - RegistrationOptions WorkspaceExecuteCommand = ExecuteCommandRegistrationOptions - - -- Text synchronisation - RegistrationOptions TextDocumentDidOpen = TextDocumentRegistrationOptions - RegistrationOptions TextDocumentDidChange = TextDocumentChangeRegistrationOptions - RegistrationOptions TextDocumentWillSave = TextDocumentRegistrationOptions - RegistrationOptions TextDocumentWillSaveWaitUntil = TextDocumentRegistrationOptions - RegistrationOptions TextDocumentDidSave = TextDocumentSaveRegistrationOptions - RegistrationOptions TextDocumentDidClose = TextDocumentRegistrationOptions - - -- Language features - RegistrationOptions TextDocumentCompletion = CompletionRegistrationOptions - RegistrationOptions TextDocumentHover = HoverRegistrationOptions - RegistrationOptions TextDocumentSignatureHelp = SignatureHelpRegistrationOptions - RegistrationOptions TextDocumentDeclaration = DeclarationRegistrationOptions - RegistrationOptions TextDocumentDefinition = DefinitionRegistrationOptions - RegistrationOptions TextDocumentTypeDefinition = TypeDefinitionRegistrationOptions - RegistrationOptions TextDocumentImplementation = ImplementationRegistrationOptions - RegistrationOptions TextDocumentReferences = ReferenceRegistrationOptions - RegistrationOptions TextDocumentDocumentHighlight = DocumentHighlightRegistrationOptions - RegistrationOptions TextDocumentDocumentSymbol = DocumentSymbolRegistrationOptions - RegistrationOptions TextDocumentCodeAction = CodeActionRegistrationOptions - RegistrationOptions TextDocumentCodeLens = CodeLensRegistrationOptions - RegistrationOptions TextDocumentDocumentLink = DocumentLinkRegistrationOptions - RegistrationOptions TextDocumentDocumentColor = DocumentColorRegistrationOptions - RegistrationOptions TextDocumentFormatting = DocumentFormattingRegistrationOptions - RegistrationOptions TextDocumentRangeFormatting = DocumentRangeFormattingRegistrationOptions - RegistrationOptions TextDocumentOnTypeFormatting = DocumentOnTypeFormattingRegistrationOptions - RegistrationOptions TextDocumentRename = RenameRegistrationOptions - RegistrationOptions TextDocumentFoldingRange = FoldingRangeRegistrationOptions - RegistrationOptions TextDocumentSelectionRange = SelectionRangeRegistrationOptions - RegistrationOptions TextDocumentPrepareCallHierarchy = CallHierarchyRegistrationOptions - RegistrationOptions TextDocumentSemanticTokens = SemanticTokensRegistrationOptions - RegistrationOptions m = Void - -data Registration (m :: Method FromClient t) = - Registration +-- | Typed registration type, with correct options. +data TRegistration (m :: Method ClientToServer t) = + TRegistration { -- | The id used to register the request. The id can be used to deregister -- the request again. - _id :: Text + _id :: Text -- | The method / capability to register for. - , _method :: SClientMethod m + , _method :: SClientMethod m -- | Options necessary for the registration. -- Make this strict to aid the pattern matching exhaustiveness checker , _registerOptions :: !(Maybe (RegistrationOptions m)) } deriving Generic -deriving instance Eq (RegistrationOptions m) => Eq (Registration m) -deriving instance Show (RegistrationOptions m) => Show (Registration m) +deriving instance Eq (RegistrationOptions m) => Eq (TRegistration m) +deriving instance Show (RegistrationOptions m) => Show (TRegistration m) +-- TODO: can we do this generically somehow? -- This generates the function -- regHelper :: SMethod m -- -> (( Show (RegistrationOptions m) @@ -127,10 +60,10 @@ deriving instance Show (RegistrationOptions m) => Show (Registration m) -- -> x makeRegHelper ''RegistrationOptions -instance ToJSON (Registration m) where - toJSON x@(Registration _ m _) = regHelper m (genericToJSON lspOptions x) +instance ToJSON (TRegistration m) where + toJSON x@(TRegistration _ m _) = regHelper m (genericToJSON lspOptions x) -data SomeRegistration = forall t (m :: Method FromClient t). SomeRegistration (Registration m) +data SomeRegistration = forall t (m :: Method ClientToServer t). SomeRegistration (TRegistration m) instance ToJSON SomeRegistration where toJSON (SomeRegistration r) = toJSON r @@ -138,42 +71,60 @@ instance ToJSON SomeRegistration where instance FromJSON SomeRegistration where parseJSON = withObject "Registration" $ \o -> do SomeClientMethod m <- o .: "method" - r <- Registration <$> o .: "id" <*> pure m <*> regHelper m (o .: "registerOptions") + r <- TRegistration <$> o .: "id" <*> pure m <*> regHelper m (o .: "registerOptions") pure (SomeRegistration r) -instance Eq SomeRegistration where - (==) = (==) `on` toJSON - instance Show SomeRegistration where - show (SomeRegistration r@(Registration _ m _)) = regHelper m (show r) + show (SomeRegistration r@(TRegistration _ m _)) = regHelper m (show r) -data RegistrationParams = - RegistrationParams { _registrations :: List SomeRegistration } - deriving (Show, Eq) - -deriveJSON lspOptions ''RegistrationParams +toUntypedRegistration :: TRegistration m -> Registration +toUntypedRegistration (TRegistration i meth opts) = Registration i (T.pack $ someMethodToMethodString $ SomeMethod meth) (Just $ regHelper meth (toJSON opts)) +toSomeRegistration :: Registration -> Maybe SomeRegistration +toSomeRegistration r = + let v = toJSON r + in case fromJSON v of + Success r' -> Just r' + _ -> Nothing -- --------------------------------------------------------------------- --- | General parameters to unregister a capability. -data Unregistration = - Unregistration +-- | Typed unregistration type. +data TUnregistration (m :: Method ClientToServer t) = + TUnregistration { -- | The id used to unregister the request or notification. Usually an id -- provided during the register request. _id :: Text -- | The method / capability to unregister for. - , _method :: SomeClientMethod - } deriving (Show, Eq) + , _method :: SMethod m + } deriving Generic + +deriving instance Eq (TUnregistration m) +deriving instance Show (TUnregistration m) + +instance ToJSON (TUnregistration m) where + toJSON x@(TUnregistration _ m) = regHelper m (genericToJSON lspOptions x) + +data SomeUnregistration = forall t (m :: Method ClientToServer t). SomeUnregistration (TUnregistration m) + +instance ToJSON SomeUnregistration where + toJSON (SomeUnregistration r) = toJSON r + +instance FromJSON SomeUnregistration where + parseJSON = withObject "Unregistration" $ \o -> do + SomeClientMethod m <- o .: "method" + r <- TUnregistration <$> o .: "id" <*> pure m + pure (SomeUnregistration r) -deriveJSON lspOptions ''Unregistration +toUntypedUnregistration :: TUnregistration m -> Unregistration +toUntypedUnregistration (TUnregistration i meth) = Unregistration i (T.pack $ someMethodToMethodString $ SomeMethod meth) -data UnregistrationParams = - UnregistrationParams - { -- | This should correctly be named @unregistrations@. However changing this - -- is a breaking change and needs to wait until we deliver a 4.x version - -- of the specification. - _unregisterations :: List Unregistration - } deriving (Show, Eq) +toSomeUnregistration :: Unregistration -> Maybe SomeUnregistration +toSomeUnregistration r = + let v = toJSON r + in case fromJSON v of + Success r' -> Just r' + _ -> Nothing -deriveJSON lspOptions ''UnregistrationParams +makeFieldsNoPrefix ''TRegistration +makeFieldsNoPrefix ''TUnregistration diff --git a/lsp-types/src/Language/LSP/Types/Rename.hs b/lsp-types/src/Language/LSP/Types/Rename.hs deleted file mode 100644 index c7aa22391..000000000 --- a/lsp-types/src/Language/LSP/Types/Rename.hs +++ /dev/null @@ -1,85 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.Rename where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Data.Scientific (Scientific) - -import Language.LSP.Types.Location -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Progress -import Language.LSP.Types.Utils - -data PrepareSupportDefaultBehavior = - PsIdentifier | - PsUnknown Scientific - deriving (Read, Show, Eq) - -instance ToJSON PrepareSupportDefaultBehavior where - toJSON PsIdentifier = Number 1 - toJSON (PsUnknown i) = Number i - -instance FromJSON PrepareSupportDefaultBehavior where - parseJSON (Number 1) = pure PsIdentifier - parseJSON _ = fail "PrepareSupportDefaultBehavior" - -data RenameClientCapabilities = - RenameClientCapabilities - { -- | Whether rename supports dynamic registration. - _dynamicRegistration :: Maybe Bool - -- | Client supports testing for validity of rename operations - -- before execution. - -- - -- Since LSP 3.12.0 - , _prepareSupport :: Maybe Bool - -- | Client supports the default behavior result - -- (`{ defaultBehavior: boolean }`). - -- - -- The value indicates the default behavior used by the client. - -- - -- @since 3.16.0 - , prepareSupportDefaultBehavior :: Maybe PrepareSupportDefaultBehavior - -- | Whether the client honors the change annotations in - -- text edits and resource operations returned via the - -- rename request's workspace edit by for example presenting - -- the workspace edit in the user interface and asking - -- for confirmation. - -- - -- @since 3.16.0 - , honorsChangeAnnotations :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''RenameClientCapabilities - -makeExtendingDatatype "RenameOptions" [''WorkDoneProgressOptions] - [("_prepareProvider", [t| Maybe Bool |])] -deriveJSON lspOptions ''RenameOptions - -makeExtendingDatatype "RenameRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''RenameOptions - ] [] -deriveJSON lspOptions ''RenameRegistrationOptions - -makeExtendingDatatype "RenameParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - ] - [("_newName", [t| Text |])] -deriveJSON lspOptions ''RenameParams - --- ----------------------------------------- - -makeExtendingDatatype "PrepareRenameParams" [''TextDocumentPositionParams] [] -deriveJSON lspOptions ''PrepareRenameParams - -data RangeWithPlaceholder = - RangeWithPlaceholder - { - _range :: Range - , _placeholder :: Text - } deriving Eq -deriveJSON lspOptions ''RangeWithPlaceholder diff --git a/lsp-types/src/Language/LSP/Types/SMethodMap.hs b/lsp-types/src/Language/LSP/Types/SMethodMap.hs index 3d2340a66..3db9af693 100644 --- a/lsp-types/src/Language/LSP/Types/SMethodMap.hs +++ b/lsp-types/src/Language/LSP/Types/SMethodMap.hs @@ -14,17 +14,19 @@ module Language.LSP.Types.SMethodMap , map ) where -import Prelude hiding (lookup, map) -import Data.IntMap (IntMap) -import qualified Data.IntMap.Strict as IntMap -import Data.Kind (Type) -import Data.Map (Map) -import qualified Data.Map.Strict as Map -import Data.Text (Text) -import GHC.Exts (Int(..), dataToTag#, Any) -import Unsafe.Coerce (unsafeCoerce) +import Data.IntMap (IntMap) +import qualified Data.IntMap.Strict as IntMap +import Data.Kind (Type) +import Data.Map (Map) +import qualified Data.Map.Strict as Map +import GHC.Exts (Any, Int (..), + dataToTag#) +import Prelude hiding (lookup, map) +import Unsafe.Coerce (unsafeCoerce) -import Language.LSP.Types.Method (Method(..), SMethod(..)) +import GHC.TypeLits (symbolVal) +import Language.LSP.Types.Internal.Generated (Method (..), + SMethod (..)) -- This type exists to avoid a dependency on 'dependent-map'. It is less -- safe (since we use 'unsafeCoerce') but much simpler and hence easier to include. @@ -35,30 +37,30 @@ data SMethodMap (v :: Method f t -> Type) = -- in the map. We do not attempt to be truly dependent here, and instead exploit -- 'usafeCoerce' to go to and from 'v Any'. -- The sole exception is 'SCustomMethod', for which we keep a separate map from - -- its 'Text' parameter (and where we can get the type indices right). - SMethodMap !(IntMap (v Any)) !(Map Text (v 'CustomMethod)) + -- its 'Text' parameter + SMethodMap !(IntMap (v Any)) !(Map String (v Any)) toIx :: SMethod a -> Int toIx k = I# (dataToTag# k) singleton :: SMethod a -> v a -> SMethodMap v -singleton (SCustomMethod t) v = SMethodMap mempty (Map.singleton t v) +singleton (SMethod_CustomMethod t) v = SMethodMap mempty (Map.singleton (symbolVal t) (unsafeCoerce v)) singleton k v = SMethodMap (IntMap.singleton (toIx k) (unsafeCoerce v)) mempty insert :: SMethod a -> v a -> SMethodMap v -> SMethodMap v -insert (SCustomMethod t) v (SMethodMap xs ys) = SMethodMap xs (Map.insert t v ys) +insert (SMethod_CustomMethod t) v (SMethodMap xs ys) = SMethodMap xs (Map.insert (symbolVal t) (unsafeCoerce v) ys) insert k v (SMethodMap xs ys) = SMethodMap (IntMap.insert (toIx k) (unsafeCoerce v) xs) ys delete :: SMethod a -> SMethodMap v -> SMethodMap v -delete (SCustomMethod t) (SMethodMap xs ys) = SMethodMap xs (Map.delete t ys) +delete (SMethod_CustomMethod t) (SMethodMap xs ys) = SMethodMap xs (Map.delete (symbolVal t) ys) delete k (SMethodMap xs ys) = SMethodMap (IntMap.delete (toIx k) xs) ys member :: SMethod a -> SMethodMap v -> Bool -member (SCustomMethod t) (SMethodMap _ ys) = Map.member t ys -member k (SMethodMap xs _) = IntMap.member (toIx k) xs +member (SMethod_CustomMethod t) (SMethodMap _ ys) = Map.member (symbolVal t) ys +member k (SMethodMap xs _) = IntMap.member (toIx k) xs lookup :: SMethod a -> SMethodMap v -> Maybe (v a) -lookup (SCustomMethod t) (SMethodMap _ ys) = Map.lookup t ys +lookup (SMethod_CustomMethod t) (SMethodMap _ ys) = unsafeCoerce (Map.lookup (symbolVal t) ys) lookup k (SMethodMap xs _) = unsafeCoerce (IntMap.lookup (toIx k) xs) map :: (forall a. u a -> v a) -> SMethodMap u -> SMethodMap v diff --git a/lsp-types/src/Language/LSP/Types/SelectionRange.hs b/lsp-types/src/Language/LSP/Types/SelectionRange.hs deleted file mode 100644 index dd72fb313..000000000 --- a/lsp-types/src/Language/LSP/Types/SelectionRange.hs +++ /dev/null @@ -1,54 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.SelectionRange where - -import Data.Aeson.TH -import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data SelectionRangeClientCapabilities = SelectionRangeClientCapabilities - { -- | Whether implementation supports dynamic registration for selection range providers. If this is set to 'True' - -- the client supports the new 'SelectionRangeRegistrationOptions' return value for the corresponding server - -- capability as well. - _dynamicRegistration :: Maybe Bool - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''SelectionRangeClientCapabilities - -makeExtendingDatatype "SelectionRangeOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''SelectionRangeOptions - -makeExtendingDatatype - "SelectionRangeRegistrationOptions" - [ ''SelectionRangeOptions, - ''TextDocumentRegistrationOptions, - ''StaticRegistrationOptions - ] - [] -deriveJSON lspOptions ''SelectionRangeRegistrationOptions - -makeExtendingDatatype - "SelectionRangeParams" - [ ''WorkDoneProgressParams, - ''PartialResultParams - ] - [ ("_textDocument", [t|TextDocumentIdentifier|]), - ("_positions", [t|List Position|]) - ] -deriveJSON lspOptions ''SelectionRangeParams - -data SelectionRange = SelectionRange - { -- | The 'range' of this selection range. - _range :: Range, - -- | The parent selection range containing this range. Therefore @parent.range@ must contain @this.range@. - _parent :: Maybe SelectionRange - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''SelectionRange diff --git a/lsp-types/src/Language/LSP/Types/SemanticTokens.hs b/lsp-types/src/Language/LSP/Types/SemanticTokens.hs index 4a6b76960..f2cb56b89 100644 --- a/lsp-types/src/Language/LSP/Types/SemanticTokens.hs +++ b/lsp-types/src/Language/LSP/Types/SemanticTokens.hs @@ -2,359 +2,70 @@ {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -{-# LANGUAGE TemplateHaskell #-} module Language.LSP.Types.SemanticTokens where -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Text (Text) +import Data.Text (Text) import Control.Monad.Except import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -import qualified Data.Algorithm.Diff as Diff -import qualified Data.Bits as Bits -import qualified Data.DList as DList -import Data.Default -import Data.Foldable hiding (length) -import qualified Data.Map as Map -import Data.Maybe (fromMaybe, - maybeToList) +import Language.LSP.Types.Internal.Generated + +import qualified Data.Algorithm.Diff as Diff +import qualified Data.Bits as Bits +import qualified Data.DList as DList +import Data.Foldable hiding (length) +import qualified Data.Map as Map +import Data.Maybe (fromMaybe, mapMaybe, + maybeToList) import Data.String -data SemanticTokenTypes = - SttNamespace - | SttType - | SttClass - | SttEnum - | SttInterface - | SttStruct - | SttTypeParameter - | SttParameter - | SttVariable - | SttProperty - | SttEnumMember - | SttEvent - | SttFunction - | SttMethod - | SttMacro - | SttKeyword - | SttModifier - | SttComment - | SttString - | SttNumber - | SttRegexp - | SttOperator - | SttUnknown Text - deriving (Show, Read, Eq, Ord) - -instance A.ToJSON SemanticTokenTypes where - toJSON SttNamespace = A.String "namespace" - toJSON SttType = A.String "type" - toJSON SttClass = A.String "class" - toJSON SttEnum = A.String "enum" - toJSON SttInterface = A.String "interface" - toJSON SttStruct = A.String "struct" - toJSON SttTypeParameter = A.String "typeParameter" - toJSON SttParameter = A.String "parameter" - toJSON SttVariable = A.String "variable" - toJSON SttProperty = A.String "property" - toJSON SttEnumMember = A.String "enumMember" - toJSON SttEvent = A.String "event" - toJSON SttFunction = A.String "function" - toJSON SttMethod = A.String "method" - toJSON SttMacro = A.String "macro" - toJSON SttKeyword = A.String "keyword" - toJSON SttModifier = A.String "modifier" - toJSON SttComment = A.String "comment" - toJSON SttString = A.String "string" - toJSON SttNumber = A.String "number" - toJSON SttRegexp = A.String "regexp" - toJSON SttOperator = A.String "operator" - toJSON (SttUnknown t) = A.String t - -instance A.FromJSON SemanticTokenTypes where - parseJSON (A.String "namespace") = pure SttNamespace - parseJSON (A.String "type") = pure SttType - parseJSON (A.String "class") = pure SttClass - parseJSON (A.String "enum") = pure SttEnum - parseJSON (A.String "interface") = pure SttInterface - parseJSON (A.String "struct") = pure SttStruct - parseJSON (A.String "typeParameter") = pure SttTypeParameter - parseJSON (A.String "parameter") = pure SttParameter - parseJSON (A.String "variable") = pure SttVariable - parseJSON (A.String "property") = pure SttProperty - parseJSON (A.String "enumMember") = pure SttEnumMember - parseJSON (A.String "event") = pure SttEvent - parseJSON (A.String "function") = pure SttFunction - parseJSON (A.String "method") = pure SttMethod - parseJSON (A.String "macro") = pure SttMacro - parseJSON (A.String "keyword") = pure SttKeyword - parseJSON (A.String "modifier") = pure SttModifier - parseJSON (A.String "comment") = pure SttComment - parseJSON (A.String "string") = pure SttString - parseJSON (A.String "number") = pure SttNumber - parseJSON (A.String "regexp") = pure SttRegexp - parseJSON (A.String "operator") = pure SttOperator - parseJSON (A.String t) = pure $ SttUnknown t - parseJSON _ = mempty - -- | The set of semantic token types which are "known" (i.e. listed in the LSP spec). knownSemanticTokenTypes :: [SemanticTokenTypes] knownSemanticTokenTypes = [ - SttNamespace - , SttType - , SttClass - , SttEnum - , SttInterface - , SttStruct - , SttTypeParameter - , SttParameter - , SttVariable - , SttProperty - , SttEnumMember - , SttEvent - , SttFunction - , SttMethod - , SttMacro - , SttKeyword - , SttModifier - , SttComment - , SttString - , SttNumber - , SttRegexp - , SttOperator + SemanticTokenTypes_Namespace + , SemanticTokenTypes_Type + , SemanticTokenTypes_Class + , SemanticTokenTypes_Enum + , SemanticTokenTypes_Interface + , SemanticTokenTypes_Struct + , SemanticTokenTypes_TypeParameter + , SemanticTokenTypes_Parameter + , SemanticTokenTypes_Variable + , SemanticTokenTypes_Property + , SemanticTokenTypes_EnumMember + , SemanticTokenTypes_Event + , SemanticTokenTypes_Function + , SemanticTokenTypes_Method + , SemanticTokenTypes_Macro + , SemanticTokenTypes_Keyword + , SemanticTokenTypes_Modifier + , SemanticTokenTypes_Comment + , SemanticTokenTypes_String + , SemanticTokenTypes_Number + , SemanticTokenTypes_Regexp + , SemanticTokenTypes_Operator ] -data SemanticTokenModifiers = - StmDeclaration - | StmDefinition - | StmReadonly - | StmStatic - | StmDeprecated - | StmAbstract - | StmAsync - | StmModification - | StmDocumentation - | StmDefaultLibrary - | StmUnknown Text - deriving (Show, Read, Eq, Ord) - -instance A.ToJSON SemanticTokenModifiers where - toJSON StmDeclaration = A.String "declaration" - toJSON StmDefinition = A.String "definition" - toJSON StmReadonly = A.String "readonly" - toJSON StmStatic = A.String "static" - toJSON StmDeprecated = A.String "deprecated" - toJSON StmAbstract = A.String "abstract" - toJSON StmAsync = A.String "async" - toJSON StmModification = A.String "modification" - toJSON StmDocumentation = A.String "documentation" - toJSON StmDefaultLibrary = A.String "defaultLibrary" - toJSON (StmUnknown t) = A.String t - -instance A.FromJSON SemanticTokenModifiers where - parseJSON (A.String "declaration") = pure StmDeclaration - parseJSON (A.String "definition") = pure StmDefinition - parseJSON (A.String "readonly") = pure StmReadonly - parseJSON (A.String "static") = pure StmStatic - parseJSON (A.String "deprecated") = pure StmDeprecated - parseJSON (A.String "abstract") = pure StmAbstract - parseJSON (A.String "async") = pure StmAsync - parseJSON (A.String "modification") = pure StmModification - parseJSON (A.String "documentation") = pure StmDocumentation - parseJSON (A.String "defaultLibrary") = pure StmDefaultLibrary - parseJSON (A.String t) = pure $ StmUnknown t - parseJSON _ = mempty - -- | The set of semantic token modifiers which are "known" (i.e. listed in the LSP spec). knownSemanticTokenModifiers :: [SemanticTokenModifiers] knownSemanticTokenModifiers = [ - StmDeclaration - , StmDefinition - , StmReadonly - , StmStatic - , StmDeprecated - , StmAbstract - , StmAsync - , StmModification - , StmDocumentation - , StmDefaultLibrary - ] - -data TokenFormat = TokenFormatRelative - deriving (Show, Read, Eq) - -instance A.ToJSON TokenFormat where - toJSON TokenFormatRelative = A.String "relative" - -instance A.FromJSON TokenFormat where - parseJSON (A.String "relative") = pure TokenFormatRelative - parseJSON _ = mempty - -data SemanticTokensLegend = SemanticTokensLegend { - -- | The token types a server uses. - _tokenTypes :: List SemanticTokenTypes, - -- | The token modifiers a server uses. - _tokenModifiers :: List SemanticTokenModifiers -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensLegend - --- We give a default legend which just lists the "known" types and modifiers in the order they're listed. -instance Default SemanticTokensLegend where - def = SemanticTokensLegend (List knownSemanticTokenTypes) (List knownSemanticTokenModifiers) - -data SemanticTokensRangeClientCapabilities = SemanticTokensRangeBool Bool | SemanticTokensRangeObj A.Value - deriving (Show, Read, Eq) -deriveJSON lspOptionsUntagged ''SemanticTokensRangeClientCapabilities - -data SemanticTokensDeltaClientCapabilities = SemanticTokensDeltaClientCapabilities { - -- | The client will send the `textDocument/semanticTokens/full/delta` - -- request if the server provides a corresponding handler. - _delta :: Maybe Bool -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensDeltaClientCapabilities - -data SemanticTokensFullClientCapabilities = SemanticTokensFullBool Bool | SemanticTokensFullDelta SemanticTokensDeltaClientCapabilities - deriving (Show, Read, Eq) -deriveJSON lspOptionsUntagged ''SemanticTokensFullClientCapabilities - -data SemanticTokensRequestsClientCapabilities = SemanticTokensRequestsClientCapabilities { - -- | The client will send the `textDocument/semanticTokens/range` request - -- if the server provides a corresponding handler. - _range :: Maybe SemanticTokensRangeClientCapabilities, - -- | The client will send the `textDocument/semanticTokens/full` request - -- if the server provides a corresponding handler. - _full :: Maybe SemanticTokensFullClientCapabilities -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensRequestsClientCapabilities - -data SemanticTokensClientCapabilities = SemanticTokensClientCapabilities { - -- | Whether implementation supports dynamic registration. If this is set to - -- `true` the client supports the new `(TextDocumentRegistrationOptions & - -- StaticRegistrationOptions)` return value for the corresponding server - -- capability as well. - _dynamicRegistration :: Maybe Bool, - - -- | Which requests the client supports and might send to the server - -- depending on the server's capability. Please note that clients might not - -- show semantic tokens or degrade some of the user experience if a range - -- or full request is advertised by the client but not provided by the - -- server. If for example the client capability `requests.full` and - -- `request.range` are both set to true but the server only provides a - -- range provider the client might not render a minimap correctly or might - -- even decide to not show any semantic tokens at all. - _requests :: SemanticTokensRequestsClientCapabilities, - - -- | The token types that the client supports. - _tokenTypes :: List SemanticTokenTypes, - - -- | The token modifiers that the client supports. - _tokenModifiers :: List SemanticTokenModifiers, - - -- | The formats the clients supports. - _formats :: List TokenFormat, - - -- | Whether the client supports tokens that can overlap each other. - _overlappingTokenSupport :: Maybe Bool, - - -- | Whether the client supports tokens that can span multiple lines. - _multilineTokenSupport :: Maybe Bool -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensClientCapabilities - -makeExtendingDatatype "SemanticTokensOptions" [''WorkDoneProgressOptions] - [ ("_legend", [t| SemanticTokensLegend |]) - , ("_range", [t| Maybe SemanticTokensRangeClientCapabilities |]) - , ("_full", [t| Maybe SemanticTokensFullClientCapabilities |]) + SemanticTokenModifiers_Declaration + , SemanticTokenModifiers_Definition + , SemanticTokenModifiers_Readonly + , SemanticTokenModifiers_Static + , SemanticTokenModifiers_Deprecated + , SemanticTokenModifiers_Abstract + , SemanticTokenModifiers_Async + , SemanticTokenModifiers_Modification + , SemanticTokenModifiers_Documentation + , SemanticTokenModifiers_DefaultLibrary ] -deriveJSON lspOptions ''SemanticTokensOptions - -makeExtendingDatatype "SemanticTokensRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''SemanticTokensOptions - , ''StaticRegistrationOptions] [] -deriveJSON lspOptions ''SemanticTokensRegistrationOptions - -makeExtendingDatatype "SemanticTokensParams" - [''WorkDoneProgressParams - , ''PartialResultParams] - [ ("_textDocument", [t| TextDocumentIdentifier |]) ] -deriveJSON lspOptions ''SemanticTokensParams - -data SemanticTokens = SemanticTokens { - -- | An optional result id. If provided and clients support delta updating - -- the client will include the result id in the next semantic token request. - -- A server can then instead of computing all semantic tokens again simply - -- send a delta. - _resultId :: Maybe Text, - - -- | The actual tokens. - _xdata :: List UInt -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokens -data SemanticTokensPartialResult = SemanticTokensPartialResult { - _xdata :: List UInt -} -deriveJSON lspOptions ''SemanticTokensPartialResult - -makeExtendingDatatype "SemanticTokensDeltaParams" - [''WorkDoneProgressParams - , ''PartialResultParams] - [ ("_textDocument", [t| TextDocumentIdentifier |]) - , ("_previousResultId", [t| Text |]) - ] -deriveJSON lspOptions ''SemanticTokensDeltaParams - -data SemanticTokensEdit = SemanticTokensEdit { - -- | The start offset of the edit. - _start :: UInt, - -- | The count of elements to remove. - _deleteCount :: UInt, - -- | The elements to insert. - _xdata :: Maybe (List UInt) -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensEdit - -data SemanticTokensDelta = SemanticTokensDelta { - _resultId :: Maybe Text, - -- | The semantic token edits to transform a previous result into a new - -- result. - _edits :: List SemanticTokensEdit -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensDelta - -data SemanticTokensDeltaPartialResult = SemantictokensDeltaPartialResult { - _edits :: List SemanticTokensEdit -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensDeltaPartialResult - -makeExtendingDatatype "SemanticTokensRangeParams" - [''WorkDoneProgressParams - , ''PartialResultParams] - [ ("_textDocument", [t| TextDocumentIdentifier |]) - , ("_range", [t| Range |]) - ] -deriveJSON lspOptions ''SemanticTokensRangeParams - -data SemanticTokensWorkspaceClientCapabilities = SemanticTokensWorkspaceClientCapabilities { - -- | Whether the client implementation supports a refresh request sent from - -- the server to the client. - -- - -- Note that this event is global and will force the client to refresh all - -- semantic tokens currently shown. It should be used with absolute care - -- and is useful for situation where a server for example detect a project - -- wide change that requires such a calculation. - _refreshSupport :: Maybe Bool -} deriving (Show, Read, Eq) -deriveJSON lspOptions ''SemanticTokensWorkspaceClientCapabilities +defaultSemanticTokensLegend :: SemanticTokensLegend +defaultSemanticTokensLegend = SemanticTokensLegend + (fmap semanticTokenTypesToValue knownSemanticTokenTypes) + (fmap semanticTokenModifiersToValue knownSemanticTokenModifiers) ---------------------------------------------------------- -- Tools for working with semantic tokens. @@ -368,7 +79,7 @@ data SemanticTokenAbsolute = SemanticTokenAbsolute { length :: UInt, tokenType :: SemanticTokenTypes, tokenModifiers :: [SemanticTokenModifiers] -} deriving (Show, Read, Eq, Ord) +} deriving (Show, Eq, Ord) -- Note: we want the Ord instance to sort the tokens textually: this is achieved due to the -- order of the constructors @@ -379,7 +90,7 @@ data SemanticTokenRelative = SemanticTokenRelative { length :: UInt, tokenType :: SemanticTokenTypes, tokenModifiers :: [SemanticTokenModifiers] -} deriving (Show, Read, Eq, Ord) +} deriving (Show, Eq, Ord) -- Note: we want the Ord instance to sort the tokens textually: this is achieved due to the -- order of the constructors @@ -415,15 +126,15 @@ absolutizeTokens xs = DList.toList $ go 0 0 xs mempty -- | Encode a series of relatively-positioned semantic tokens into an integer array following the given legend. encodeTokens :: SemanticTokensLegend -> [SemanticTokenRelative] -> Either Text [UInt] -encodeTokens SemanticTokensLegend{_tokenTypes=List tts,_tokenModifiers=List tms} sts = +encodeTokens SemanticTokensLegend{_tokenTypes=tts,_tokenModifiers=tms} sts = DList.toList . DList.concat <$> traverse encodeToken sts where -- Note that there's no "fast" version of these (e.g. backed by an IntMap or similar) -- in general, due to the possibility of unknown token types which are only identified by strings. tyMap :: Map.Map SemanticTokenTypes UInt - tyMap = Map.fromList $ zip tts [0..] + tyMap = Map.fromList $ zip (fmap valueToSemanticTokenTypes tts) [0..] modMap :: Map.Map SemanticTokenModifiers Int - modMap = Map.fromList $ zip tms [0..] + modMap = Map.fromList $ zip (fmap valueToSemanticTokenModifiers tms) [0..] lookupTy :: SemanticTokenTypes -> Either Text UInt lookupTy ty = case Map.lookup ty tyMap of @@ -444,7 +155,7 @@ encodeTokens SemanticTokensLegend{_tokenTypes=List tts,_tokenModifiers=List tms} pure [dl, dc, len, tycode, fromIntegral combinedModcode ] -- This is basically 'SemanticTokensEdit', but slightly easier to work with. --- | An edit to a buffer of items. +-- | An edit to a buffer of items. data Edit a = Edit { editStart :: UInt, editDeleteCount :: UInt, editInsertions :: [a] } deriving (Read, Show, Eq, Ord) @@ -488,13 +199,12 @@ computeEdits l r = DList.toList $ go 0 Nothing (Diff.getGroupedDiff l r) mempty makeSemanticTokens :: SemanticTokensLegend -> [SemanticTokenAbsolute] -> Either Text SemanticTokens makeSemanticTokens legend sts = do encoded <- encodeTokens legend $ relativizeTokens sts - pure $ SemanticTokens Nothing (List encoded) + pure $ SemanticTokens Nothing encoded -- | Convenience function for making a 'SemanticTokensDelta' from a previous and current 'SemanticTokens'. -- The resulting 'SemanticTokensDelta' lacks a result ID, which must be set separately if you are using that. makeSemanticTokensDelta :: SemanticTokens -> SemanticTokens -> SemanticTokensDelta -makeSemanticTokensDelta SemanticTokens{_xdata=List prevTokens} SemanticTokens{_xdata=List curTokens} = +makeSemanticTokensDelta SemanticTokens{_data_=prevTokens} SemanticTokens{_data_=curTokens} = let edits = computeEdits prevTokens curTokens - stEdits = fmap (\(Edit s ds as) -> SemanticTokensEdit s ds (Just $ List as)) edits - in SemanticTokensDelta Nothing (List stEdits) - + stEdits = fmap (\(Edit s ds as) -> SemanticTokensEdit s ds (Just as)) edits + in SemanticTokensDelta Nothing stEdits diff --git a/lsp-types/src/Language/LSP/Types/ServerCapabilities.hs b/lsp-types/src/Language/LSP/Types/ServerCapabilities.hs deleted file mode 100644 index 70fb50233..000000000 --- a/lsp-types/src/Language/LSP/Types/ServerCapabilities.hs +++ /dev/null @@ -1,137 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeOperators #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.ServerCapabilities where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.CallHierarchy -import Language.LSP.Types.CodeAction -import Language.LSP.Types.CodeLens -import Language.LSP.Types.Command -import Language.LSP.Types.Common -import Language.LSP.Types.Completion -import Language.LSP.Types.Declaration -import Language.LSP.Types.Definition -import Language.LSP.Types.DocumentColor -import Language.LSP.Types.DocumentHighlight -import Language.LSP.Types.DocumentLink -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.FoldingRange -import Language.LSP.Types.Formatting -import Language.LSP.Types.Hover -import Language.LSP.Types.Implementation -import Language.LSP.Types.References -import Language.LSP.Types.Rename -import Language.LSP.Types.SelectionRange -import Language.LSP.Types.SemanticTokens -import Language.LSP.Types.SignatureHelp -import Language.LSP.Types.TextDocument -import Language.LSP.Types.TypeDefinition -import Language.LSP.Types.Utils -import Language.LSP.Types.WorkspaceSymbol - --- --------------------------------------------------------------------- - -data WorkspaceFoldersServerCapabilities = - WorkspaceFoldersServerCapabilities - { -- | The server has support for workspace folders - _supported :: Maybe Bool - -- | Whether the server wants to receive workspace folder - -- change notifications. - -- If a strings is provided the string is treated as a ID - -- under which the notification is registered on the client - -- side. The ID can be used to unregister for these events - -- using the `client/unregisterCapability` request. - , _changeNotifications :: Maybe (Text |? Bool) - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceFoldersServerCapabilities - -data WorkspaceServerCapabilities = - WorkspaceServerCapabilities - { -- | The server supports workspace folder. Since LSP 3.6 - -- - -- @since 0.7.0.0 - _workspaceFolders :: Maybe WorkspaceFoldersServerCapabilities - } - deriving (Show, Read, Eq) -deriveJSON lspOptions ''WorkspaceServerCapabilities - -data ServerCapabilities = - ServerCapabilities - { -- | Defines how text documents are synced. Is either a detailed structure - -- defining each notification or for backwards compatibility the - -- 'TextDocumentSyncKind' number. - -- If omitted it defaults to 'TdSyncNone'. - _textDocumentSync :: Maybe (TextDocumentSyncOptions |? TextDocumentSyncKind) - -- | The server provides hover support. - , _hoverProvider :: Maybe (Bool |? HoverOptions) - -- | The server provides completion support. - , _completionProvider :: Maybe CompletionOptions - -- | The server provides signature help support. - , _signatureHelpProvider :: Maybe SignatureHelpOptions - -- | The server provides go to declaration support. - -- - -- Since LSP 3.14.0 - , _declarationProvider :: Maybe (Bool |? DeclarationOptions |? DeclarationRegistrationOptions) - -- | The server provides goto definition support. - , _definitionProvider :: Maybe (Bool |? DefinitionOptions) - -- | The server provides Goto Type Definition support. Since LSP 3.6 - -- - -- @since 0.7.0.0 - , _typeDefinitionProvider :: Maybe (Bool |? TypeDefinitionOptions |? TypeDefinitionRegistrationOptions) - -- | The server provides Goto Implementation support. Since LSP 3.6 - -- - -- @since 0.7.0.0 - , _implementationProvider :: Maybe (Bool |? ImplementationOptions |? ImplementationRegistrationOptions) - -- | The server provides find references support. - , _referencesProvider :: Maybe (Bool |? ReferenceOptions) - -- | The server provides document highlight support. - , _documentHighlightProvider :: Maybe (Bool |? DocumentHighlightOptions) - -- | The server provides document symbol support. - , _documentSymbolProvider :: Maybe (Bool |? DocumentSymbolOptions) - -- | The server provides code actions. - , _codeActionProvider :: Maybe (Bool |? CodeActionOptions) - -- | The server provides code lens. - , _codeLensProvider :: Maybe CodeLensOptions - -- | The server provides document link support. - , _documentLinkProvider :: Maybe DocumentLinkOptions - -- | The server provides color provider support. Since LSP 3.6 - -- - -- @since 0.7.0.0 - , _colorProvider :: Maybe (Bool |? DocumentColorOptions |? DocumentColorRegistrationOptions) - -- | The server provides document formatting. - , _documentFormattingProvider :: Maybe (Bool |? DocumentFormattingOptions) - -- | The server provides document range formatting. - , _documentRangeFormattingProvider :: Maybe (Bool |? DocumentRangeFormattingOptions) - -- | The server provides document formatting on typing. - , _documentOnTypeFormattingProvider :: Maybe DocumentOnTypeFormattingOptions - -- | The server provides rename support. - , _renameProvider :: Maybe (Bool |? RenameOptions) - -- | The server provides folding provider support. Since LSP 3.10 - -- - -- @since 0.7.0.0 - , _foldingRangeProvider :: Maybe (Bool |? FoldingRangeOptions |? FoldingRangeRegistrationOptions) - -- | The server provides execute command support. - , _executeCommandProvider :: Maybe ExecuteCommandOptions - -- | The server provides selection range support. Since LSP 3.15 - , _selectionRangeProvider :: Maybe (Bool |? SelectionRangeOptions |? SelectionRangeRegistrationOptions) - -- | The server provides call hierarchy support. - , _callHierarchyProvider :: Maybe (Bool |? CallHierarchyOptions |? CallHierarchyRegistrationOptions) - -- | The server provides semantic tokens support. - -- - -- @since 3.16.0 - , _semanticTokensProvider :: Maybe (SemanticTokensOptions |? SemanticTokensRegistrationOptions) - -- | The server provides workspace symbol support. - , _workspaceSymbolProvider :: Maybe (Bool |? WorkspaceSymbolOptions) - -- | Workspace specific server capabilities - , _workspace :: Maybe WorkspaceServerCapabilities - -- | Experimental server capabilities. - , _experimental :: Maybe Value - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ServerCapabilities diff --git a/lsp-types/src/Language/LSP/Types/SignatureHelp.hs b/lsp-types/src/Language/LSP/Types/SignatureHelp.hs deleted file mode 100644 index 4d7955957..000000000 --- a/lsp-types/src/Language/LSP/Types/SignatureHelp.hs +++ /dev/null @@ -1,207 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} --- | Signature Help Request --- https://github.com/Microsoft/language-server-protocol/blob/master/protocol.md#signature-help-request -module Language.LSP.Types.SignatureHelp where - -import Data.Aeson -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Common -import Language.LSP.Types.MarkupContent -import Language.LSP.Types.Progress -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils -import Control.Applicative (Alternative((<|>))) - --- ------------------------------------- - -data SignatureHelpParameterInformation = - SignatureHelpParameterInformation - { -- | The client supports processing label offsets instead of a simple - -- label string. - -- - -- @since 3.14.0 - _labelOffsetSupport :: Maybe Bool - } - deriving (Read, Show, Eq) -deriveJSON lspOptions ''SignatureHelpParameterInformation - -data SignatureHelpSignatureInformation = - SignatureHelpSignatureInformation - { -- | Client supports the follow content formats for the documentation - -- property. The order describes the preferred format of the client. - _documentationFormat :: Maybe (List MarkupKind) - -- | Client capabilities specific to parameter information. - , _parameterInformation :: Maybe SignatureHelpParameterInformation - -- | The client supports the `activeParameter` property on - -- 'SignatureInformation' literal. - -- - -- @since 3.16.0 - , _activeParameterSuport :: Maybe Bool - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''SignatureHelpSignatureInformation - -data SignatureHelpClientCapabilities = - SignatureHelpClientCapabilities - { -- | Whether signature help supports dynamic registration. - _dynamicRegistration :: Maybe Bool - -- | The client supports the following 'SignatureInformation' - -- specific properties. - , _signatureInformation :: Maybe SignatureHelpSignatureInformation - -- | The client supports to send additional context information for a - -- @textDocument/signatureHelp@ request. A client that opts into - -- contextSupport will also support the '_retriggerCharacters' on - -- 'SignatureHelpOptions'. - -- - -- @since 3.15.0 - , _contextSupport :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''SignatureHelpClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "SignatureHelpOptions" [''WorkDoneProgressOptions] - [ ("_triggerCharacters", [t| Maybe (List Text) |]) - , ("_retriggerCharacters", [t| Maybe (List Text) |]) - ] -deriveJSON lspOptions ''SignatureHelpOptions - -makeExtendingDatatype "SignatureHelpRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''SignatureHelpOptions - ] [] -deriveJSON lspOptions ''SignatureHelpRegistrationOptions - --- ------------------------------------- - -data SignatureHelpDoc = SignatureHelpDocString Text | SignatureHelpDocMarkup MarkupContent - deriving (Read,Show,Eq) - -deriveJSON lspOptionsUntagged ''SignatureHelpDoc - --- ------------------------------------- - -data ParameterLabel = ParameterLabelString Text | ParameterLabelOffset UInt UInt - deriving (Read,Show,Eq) - -instance ToJSON ParameterLabel where - toJSON (ParameterLabelString t) = toJSON t - toJSON (ParameterLabelOffset l h) = toJSON [l, h] - -instance FromJSON ParameterLabel where - parseJSON x = ParameterLabelString <$> parseJSON x <|> parseInterval x - where - parseInterval v@(Array _) = do - is <- parseJSON v - case is of - [l, h] -> pure $ ParameterLabelOffset l h - _ -> fail "ParameterLabel" - parseInterval _ = fail "ParameterLabel" - --- ------------------------------------- - -{-| -Represents a parameter of a callable-signature. A parameter can -have a label and a doc-comment. --} -data ParameterInformation = - ParameterInformation - { _label :: ParameterLabel -- ^ The label of this parameter information. - , _documentation :: Maybe SignatureHelpDoc -- ^ The human-readable doc-comment of this parameter. - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''ParameterInformation - --- ------------------------------------- - -{-| -Represents the signature of something callable. A signature -can have a label, like a function-name, a doc-comment, and -a set of parameters. --} -data SignatureInformation = - SignatureInformation - { _label :: Text -- ^ The label of the signature. - , _documentation :: Maybe SignatureHelpDoc -- ^ The human-readable doc-comment of this signature. - , _parameters :: Maybe (List ParameterInformation) -- ^ The parameters of this signature. - , _activeParameter :: Maybe UInt -- ^ The index of the active parameter. - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''SignatureInformation - - -{-| -Signature help represents the signature of something -callable. There can be multiple signature but only one -active and only one active parameter. --} -data SignatureHelp = - SignatureHelp - { _signatures :: List SignatureInformation -- ^ One or more signatures. - , _activeSignature :: Maybe UInt -- ^ The active signature. - , _activeParameter :: Maybe UInt -- ^ The active parameter of the active signature. - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''SignatureHelp - --- ------------------------------------- - --- | How a signature help was triggered. --- --- @since 3.15.0 -data SignatureHelpTriggerKind = SHTKInvoked -- ^ Signature help was invoked manually by the user or by a command. - | SHTKTriggerCharacter -- ^ Signature help was triggered by a trigger character. - | SHTKContentChange -- ^ Signature help was triggered by the cursor moving or by the document content changing. - deriving (Read,Show,Eq) - -instance ToJSON SignatureHelpTriggerKind where - toJSON SHTKInvoked = Number 1 - toJSON SHTKTriggerCharacter = Number 2 - toJSON SHTKContentChange = Number 3 - -instance FromJSON SignatureHelpTriggerKind where - parseJSON (Number 1) = pure SHTKInvoked - parseJSON (Number 2) = pure SHTKTriggerCharacter - parseJSON (Number 3) = pure SHTKContentChange - parseJSON _ = fail "SignatureHelpTriggerKind" - --- | Additional information about the context in which a signature help request --- was triggered. --- --- @since 3.15.0 -data SignatureHelpContext = - SignatureHelpContext - { -- | Action that caused signature help to be triggered. - _triggerKind :: SignatureHelpTriggerKind - -- | Character that caused signature help to be triggered. This is - -- undefined when @triggerKind !== - -- SignatureHelpTriggerKind.TriggerCharacter@ - , _triggerCharacter :: Maybe Text - -- | 'True' if signature help was already showing when it was triggered. - -- - -- Retriggers occur when the signature help is already active and can be - -- caused by actions such as typing a trigger character, a cursor move, or - -- document content changes. - , _isRetrigger :: Bool - -- | The currently active 'SignatureHelp'. - -- - -- The '_activeSignatureHelp' has its @SignatureHelp.activeSignature@ - -- field updated based on the user navigating through available - -- signatures. - , _activeSignatureHelp :: Maybe SignatureHelp - } - deriving (Read,Show,Eq) -deriveJSON lspOptions ''SignatureHelpContext - -makeExtendingDatatype "SignatureHelpParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - ] - [ ("_context", [t| Maybe SignatureHelpContext |]) - ] -deriveJSON lspOptions ''SignatureHelpParams - - diff --git a/lsp-types/src/Language/LSP/Types/StaticRegistrationOptions.hs b/lsp-types/src/Language/LSP/Types/StaticRegistrationOptions.hs deleted file mode 100644 index e32bd6e3a..000000000 --- a/lsp-types/src/Language/LSP/Types/StaticRegistrationOptions.hs +++ /dev/null @@ -1,13 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} --- Cyclic dependencies mean we have to put poor StaticRegistrationOptions on its own -module Language.LSP.Types.StaticRegistrationOptions where - -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Utils - -data StaticRegistrationOptions = - StaticRegistrationOptions - { _id :: Maybe Text - } deriving (Read,Show,Eq) -deriveJSON lspOptions ''StaticRegistrationOptions diff --git a/lsp-types/src/Language/LSP/Types/TextDocument.hs b/lsp-types/src/Language/LSP/Types/TextDocument.hs deleted file mode 100644 index 69bbe0470..000000000 --- a/lsp-types/src/Language/LSP/Types/TextDocument.hs +++ /dev/null @@ -1,264 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeOperators #-} -module Language.LSP.Types.TextDocument where - -import Data.Aeson -import Data.Aeson.TH -import Data.Default -import Data.Text ( Text ) - -import Language.LSP.Types.Common -import Language.LSP.Types.DocumentFilter -import Language.LSP.Types.Location -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils - --- --------------------------------------------------------------------- - -data TextDocumentIdentifier = - TextDocumentIdentifier - { _uri :: Uri - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''TextDocumentIdentifier - -type TextDocumentVersion = Maybe Int32 - -makeExtendingDatatype "VersionedTextDocumentIdentifier" [''TextDocumentIdentifier] - [ ("_version", [t| TextDocumentVersion |])] -deriveJSON lspOptions ''VersionedTextDocumentIdentifier - -data TextDocumentItem = - TextDocumentItem { - _uri :: Uri - , _languageId :: Text - , _version :: Int32 - , _text :: Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentItem - --- --------------------------------------------------------------------- - -data TextDocumentPositionParams = - TextDocumentPositionParams - { -- | The text document. - _textDocument :: TextDocumentIdentifier - , -- | The position inside the text document. - _position :: Position - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentPositionParams - --- ------------------------------------- - --- Text document synchronisation - - -data TextDocumentSyncClientCapabilities = - TextDocumentSyncClientCapabilities - { -- | Whether text document synchronization supports dynamic registration. - _dynamicRegistration :: Maybe Bool - - -- | The client supports sending will save notifications. - , _willSave :: Maybe Bool - - -- | The client supports sending a will save request and waits for a - -- response providing text edits which will be applied to the document - -- before it is saved. - , _willSaveWaitUntil :: Maybe Bool - - -- | The client supports did save notifications. - , _didSave :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentSyncClientCapabilities - -instance Default TextDocumentSyncClientCapabilities where - def = TextDocumentSyncClientCapabilities def def def def - --- ------------------------------------- - -data SaveOptions = - SaveOptions - { -- | The client is supposed to include the content on save. - _includeText :: Maybe Bool - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''SaveOptions - --- ------------------------------------- - --- | Defines how the host (editor) should sync document changes to the language server. -data TextDocumentSyncKind - = -- | Documents should not be synced at all. - TdSyncNone - | -- | Documents are synced by always sending the full content of the document. - TdSyncFull - | -- | Documents are synced by sending the full content on open. After that only incremental updates to the document are send. - TdSyncIncremental - deriving (Read, Eq, Show) - -instance ToJSON TextDocumentSyncKind where - toJSON TdSyncNone = Number 0 - toJSON TdSyncFull = Number 1 - toJSON TdSyncIncremental = Number 2 - -instance FromJSON TextDocumentSyncKind where - parseJSON (Number 0) = pure TdSyncNone - parseJSON (Number 1) = pure TdSyncFull - parseJSON (Number 2) = pure TdSyncIncremental - parseJSON _ = fail "TextDocumentSyncKind" - -data TextDocumentSyncOptions = - TextDocumentSyncOptions - { -- | Open and close notifications are sent to the server. If omitted open - -- close notification should not be sent. - _openClose :: Maybe Bool - , -- | Change notifications are sent to the server. See - -- TextDocumentSyncKind.None, TextDocumentSyncKind.Full - -- and TextDocumentSyncKind.Incremental. If omitted it defaults to - -- TextDocumentSyncKind.None. - _change :: Maybe TextDocumentSyncKind - -- | If present will save notifications are sent to the server. If omitted the notification should not be - -- sent. - , _willSave :: Maybe Bool - -- | If present will save wait until requests are sent to the server. If omitted the request should not be - -- sent. - , _willSaveWaitUntil :: Maybe Bool - -- | If present save notifications are sent to the server. If omitted the - -- notification should not be sent. - , _save :: Maybe (Bool |? SaveOptions) - } deriving (Show, Read, Eq) -deriveJSON lspOptions ''TextDocumentSyncOptions - --- ------------------------------------- - -{- -Since most of the registration options require to specify a document selector -there is a base interface that can be used. --} - -data TextDocumentRegistrationOptions = - TextDocumentRegistrationOptions - { _documentSelector :: Maybe DocumentSelector - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentRegistrationOptions - --- ------------------------------------- - -data DidOpenTextDocumentParams = - DidOpenTextDocumentParams - { -- | The document that was opened. - _textDocument :: TextDocumentItem - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DidOpenTextDocumentParams - --- ------------------------------------- - -makeExtendingDatatype "TextDocumentChangeRegistrationOptions" - [''TextDocumentRegistrationOptions] - [("_syncKind", [t| TextDocumentSyncKind |])] - -deriveJSON lspOptions ''TextDocumentChangeRegistrationOptions - -data TextDocumentContentChangeEvent = - TextDocumentContentChangeEvent - { -- | The range of the document that changed. - _range :: Maybe Range - -- | The optional length of the range that got replaced. - -- Deprecated, use _range instead - , _rangeLength :: Maybe UInt - -- | The new text for the provided range, if provided. - -- Otherwise the new text of the whole document. - , _text :: Text - } - deriving (Read,Show,Eq) - -deriveJSON lspOptions ''TextDocumentContentChangeEvent - --- ------------------------------------- - -data DidChangeTextDocumentParams = - DidChangeTextDocumentParams - { -- | The document that did change. The version number points - -- to the version after all provided content changes have - -- been applied. - _textDocument :: VersionedTextDocumentIdentifier - -- | The actual content changes. The content changes describe single state changes - -- to the document. So if there are two content changes c1 (at array index 0) and - -- c2 (at array index 1) for a document in state S then c1 moves the document from - -- S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed - -- on the state S'. - -- - -- To mirror the content of a document using change events use the following approach: - -- - start with the same initial content - -- - apply the 'textDocument/didChange' notifications in the order you recevie them. - -- - apply the `TextDocumentContentChangeEvent`s in a single notification in the order - -- you receive them. - , _contentChanges :: List TextDocumentContentChangeEvent - } deriving (Show,Read,Eq) - -deriveJSON lspOptions ''DidChangeTextDocumentParams - --- ------------------------------------- - -data TextDocumentSaveReason - = SaveManual - -- ^ Manually triggered, e.g. by the user pressing save, by starting - -- debugging, or by an API call. - | SaveAfterDelay -- ^ Automatic after a delay - | SaveFocusOut -- ^ When the editor lost focus - deriving (Show, Read, Eq) - -instance ToJSON TextDocumentSaveReason where - toJSON SaveManual = Number 1 - toJSON SaveAfterDelay = Number 2 - toJSON SaveFocusOut = Number 3 - -instance FromJSON TextDocumentSaveReason where - parseJSON (Number 1) = pure SaveManual - parseJSON (Number 2) = pure SaveAfterDelay - parseJSON (Number 3) = pure SaveFocusOut - parseJSON _ = fail "TextDocumentSaveReason" - -data WillSaveTextDocumentParams = - WillSaveTextDocumentParams - { -- | The document that will be saved. - _textDocument :: TextDocumentIdentifier - -- | The 'TextDocumentSaveReason'. - , _reason :: TextDocumentSaveReason - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WillSaveTextDocumentParams - --- ------------------------------------- - - -makeExtendingDatatype "TextDocumentSaveRegistrationOptions" - [''TextDocumentRegistrationOptions] - [("_includeText", [t| Maybe Bool |])] - -deriveJSON lspOptions ''TextDocumentSaveRegistrationOptions - -data DidSaveTextDocumentParams = - DidSaveTextDocumentParams - { -- | The document that was saved. - _textDocument :: TextDocumentIdentifier - -- | Optional the content when saved. Depends on the includeText value - -- when the save notification was requested. - , _text :: Maybe Text - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''DidSaveTextDocumentParams - --- ------------------------------------- - -data DidCloseTextDocumentParams = - DidCloseTextDocumentParams - { -- | The document that was closed. - _textDocument :: TextDocumentIdentifier - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''DidCloseTextDocumentParams diff --git a/lsp-types/src/Language/LSP/Types/TypeDefinition.hs b/lsp-types/src/Language/LSP/Types/TypeDefinition.hs deleted file mode 100644 index 7eef8676d..000000000 --- a/lsp-types/src/Language/LSP/Types/TypeDefinition.hs +++ /dev/null @@ -1,42 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} - -module Language.LSP.Types.TypeDefinition where - -import Data.Aeson.TH -import Language.LSP.Types.Progress -import Language.LSP.Types.StaticRegistrationOptions -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Utils - -data TypeDefinitionClientCapabilities = TypeDefinitionClientCapabilities - { -- | Whether implementation supports dynamic registration. If this is set - -- to 'True' - -- the client supports the new 'TypeDefinitionRegistrationOptions' return - -- value for the corresponding server capability as well. - _dynamicRegistration :: Maybe Bool, - -- | The client supports additional metadata in the form of definition links. - -- - -- Since LSP 3.14.0 - _linkSupport :: Maybe Bool - } - deriving (Read, Show, Eq) - -deriveJSON lspOptions ''TypeDefinitionClientCapabilities - -makeExtendingDatatype "TypeDefinitionOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''TypeDefinitionOptions - -makeExtendingDatatype "TypeDefinitionRegistrationOptions" - [ ''TextDocumentRegistrationOptions - , ''TypeDefinitionOptions - , ''StaticRegistrationOptions - ] [] -deriveJSON lspOptions ''TypeDefinitionRegistrationOptions - -makeExtendingDatatype "TypeDefinitionParams" - [ ''TextDocumentPositionParams - , ''WorkDoneProgressParams - , ''PartialResultParams - ] [] -deriveJSON lspOptions ''TypeDefinitionParams diff --git a/lsp-types/src/Language/LSP/Types/Uri.hs b/lsp-types/src/Language/LSP/Types/Uri.hs index c7235d26e..fe1681b30 100644 --- a/lsp-types/src/Language/LSP/Types/Uri.hs +++ b/lsp-types/src/Language/LSP/Types/Uri.hs @@ -1,6 +1,7 @@ {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} diff --git a/lsp-types/src/Language/LSP/Types/Utils.hs b/lsp-types/src/Language/LSP/Types/Utils.hs index 0039118b5..ac471571a 100644 --- a/lsp-types/src/Language/LSP/Types/Utils.hs +++ b/lsp-types/src/Language/LSP/Types/Utils.hs @@ -1,20 +1,20 @@ -{-# LANGUAGE RankNTypes #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE TemplateHaskell #-} -- | Internal helpers for generating definitions module Language.LSP.Types.Utils ( rdrop , makeSingletonFromJSON , makeRegHelper - , makeExtendingDatatype , lspOptions , lspOptionsUntagged ) where -import Control.Monad -import Data.Aeson -import Data.List -import Language.Haskell.TH +import Control.Monad +import Data.Aeson +import Data.List +import Data.Maybe (mapMaybe) +import Language.Haskell.TH -- --------------------------------------------------------------------- @@ -24,10 +24,10 @@ rdrop cnt = reverse . drop cnt . reverse -- | Given a wrapper and a singleton GADT, construct FromJSON -- instances for each constructor return type by invoking the -- FromJSON instance for the wrapper and unwrapping -makeSingletonFromJSON :: Name -> Name -> Q [Dec] -makeSingletonFromJSON wrap gadt = do +makeSingletonFromJSON :: Name -> Name -> [Name] -> Q [Dec] +makeSingletonFromJSON wrap gadt skip = do TyConI (DataD _ _ _ _ cons _) <- reify gadt - concat <$> mapM (makeInst wrap) cons + concat <$> (sequence $ mapMaybe (makeInst wrap skip) cons) {- instance FromJSON (SMethod $method) where @@ -35,33 +35,34 @@ instance FromJSON (SMethod $method) where SomeMethod $singleton-method -> pure $singleton-method _ -> mempty -} -makeInst :: Name -> Con -> Q [Dec] -makeInst wrap (GadtC [sConstructor] args t) = do +makeInst :: Name -> [Name] -> Con -> Maybe (Q [Dec]) +makeInst _ skip (GadtC [sConstructor] _ _) | sConstructor `elem` skip = Nothing +makeInst wrap _ (GadtC [sConstructor] args t) = Just $ do ns <- replicateM (length args) (newName "x") let wrappedPat = conP wrap [conP sConstructor (map varP ns)] unwrappedE = pure $ foldl' AppE (ConE sConstructor) (map VarE ns) [d| instance FromJSON $(pure t) where parseJSON = parseJSON >=> \case $wrappedPat -> pure $unwrappedE - _ -> mempty + _ -> mempty |] -makeInst wrap (ForallC _ _ con) = makeInst wrap con -- Cancel and Custom requests -makeInst _ _ = fail "makeInst only defined for GADT constructors" +makeInst wrap skip (ForallC _ _ con) = makeInst wrap skip con -- Cancel and Custom requests +makeInst _ _ _ = Just $ fail "makeInst only defined for GADT constructors" makeRegHelper :: Name -> DecsQ makeRegHelper regOptTypeName = do Just sMethodTypeName <- lookupTypeName "SMethod" - Just fromClientName <- lookupValueName "FromClient" + Just fromClientName <- lookupValueName "ClientToServer" TyConI (DataD _ _ _ _ allCons _) <- reify sMethodTypeName let isConsFromClient (GadtC _ _ (AppT _ method)) = isMethodFromClient method - isConsFromClient _ = return False + isConsFromClient _ = return False isMethodFromClient :: Type -> Q Bool isMethodFromClient (PromotedT method) = do DataConI _ typ _ <- reify method case typ of AppT (AppT _ (PromotedT n)) _ -> return $ n == fromClientName - _ -> return False + _ -> return False isMethodFromClient _ = fail "Didn't expect this type of Method!" cons <- filterM isConsFromClient allCons @@ -82,28 +83,6 @@ makeRegHelper regOptTypeName = do -> x |] return [typSig, fun] --- | @makeExtendingDatatype name extends fields@ generates a record datatype --- that contains all the fields of @extends@, plus the additional fields in --- @fields@. --- e.g. --- data Foo = { a :: Int } --- makeExtendingDatatype "bar" [''Foo] [("b", [t| String |])] --- Will generate --- data Bar = { a :: Int, b :: String } -makeExtendingDatatype :: String -> [Name] -> [(String, TypeQ)] -> DecsQ -makeExtendingDatatype datatypeNameStr extends fields = do - extendFields <- fmap concat $ forM extends $ \e -> do - TyConI (DataD _ _ _ _ [RecC _ eFields] _) <- reify e - return eFields - let datatypeName = mkName datatypeNameStr - insts = [[t| Read |], [t| Show |], [t| Eq |]] - constructor = recC datatypeName combinedFields - userFields = flip map fields $ \(s, typ) -> do - varBangType (mkName s) (bangType (bang noSourceUnpackedness noSourceStrictness) typ) - combinedFields = (map pure extendFields) <> userFields - derivs = [derivClause Nothing insts] - (\a -> [a]) <$> dataD (cxt []) datatypeName [] Nothing [constructor] derivs - -- | Standard options for use when generating JSON instances -- NOTE: This needs to be in a separate file because of the TH stage restriction lspOptions :: Options @@ -115,7 +94,7 @@ lspOptions = defaultOptions { omitNothingFields = True, fieldLabelModifier = mod -- fixes up the json derivation modifier "_xdata" = "data" modifier "_xtype" = "type" - modifier xs = drop 1 xs + modifier xs = drop 1 xs -- | Standard options for use when generating JSON instances for an untagged union lspOptionsUntagged :: Options diff --git a/lsp-types/src/Language/LSP/Types/WatchedFiles.hs b/lsp-types/src/Language/LSP/Types/WatchedFiles.hs deleted file mode 100644 index 38a16bf6d..000000000 --- a/lsp-types/src/Language/LSP/Types/WatchedFiles.hs +++ /dev/null @@ -1,113 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.WatchedFiles where - -import Data.Aeson -import Data.Aeson.TH -import Data.Bits -import Data.Scientific -import Language.LSP.Types.Common -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils -import Data.Text (Text) - --- ------------------------------------- - -data DidChangeWatchedFilesClientCapabilities = DidChangeWatchedFilesClientCapabilities - { -- | Did change watched files notification supports dynamic - -- registration. - _dynamicRegistration :: Maybe Bool - } - deriving (Show, Read, Eq) -deriveJSON lspOptions ''DidChangeWatchedFilesClientCapabilities - --- | Describe options to be used when registering for file system change events. -data DidChangeWatchedFilesRegistrationOptions = - DidChangeWatchedFilesRegistrationOptions - { -- | The watchers to register. - _watchers :: List FileSystemWatcher - } deriving (Show, Read, Eq) - -data FileSystemWatcher = - FileSystemWatcher - { -- | The glob pattern to watch. - -- Glob patterns can have the following syntax: - -- - @*@ to match one or more characters in a path segment - -- - @?@ to match on one character in a path segment - -- - @**@ to match any number of path segments, including none - -- - @{}@ to group conditions (e.g. @**​/*.{ts,js}@ matches all TypeScript and JavaScript files) - -- - @[]@ to declare a range of characters to match in a path segment (e.g., @example.[0-9]@ to match on @example.0@, @example.1@, …) - -- - @[!...]@ to negate a range of characters to match in a path segment (e.g., @example.[!0-9]@ to match on @example.a@, @example.b@, but not @example.0@) - _globPattern :: Text, - -- | The kind of events of interest. If omitted it defaults - -- to WatchKind.Create | WatchKind.Change | WatchKind.Delete - -- which is 7. - _kind :: Maybe WatchKind - } deriving (Show, Read, Eq) - -data WatchKind = - WatchKind { - -- | Watch for create events - _watchCreate :: Bool, - -- | Watch for change events - _watchChange :: Bool, - -- | Watch for delete events - _watchDelete :: Bool - } deriving (Show, Read, Eq) - -instance ToJSON WatchKind where - toJSON wk = Number (createNum + changeNum + deleteNum) - where - createNum = if _watchCreate wk then 0x1 else 0x0 - changeNum = if _watchChange wk then 0x2 else 0x0 - deleteNum = if _watchDelete wk then 0x4 else 0x0 - -instance FromJSON WatchKind where - parseJSON (Number n) - | Right i <- floatingOrInteger n :: Either Double Int - , 0 <= i && i <= 7 = - pure $ WatchKind (testBit i 0x0) (testBit i 0x1) (testBit i 0x2) - | otherwise = fail "WatchKind" - parseJSON _ = fail "WatchKind" - -deriveJSON lspOptions ''FileSystemWatcher -deriveJSON lspOptions ''DidChangeWatchedFilesRegistrationOptions --- | The file event type. -data FileChangeType = FcCreated -- ^ The file got created. - | FcChanged -- ^ The file got changed. - | FcDeleted -- ^ The file got deleted. - deriving (Read,Show,Eq) - -instance ToJSON FileChangeType where - toJSON FcCreated = Number 1 - toJSON FcChanged = Number 2 - toJSON FcDeleted = Number 3 - -instance FromJSON FileChangeType where - parseJSON (Number 1) = pure FcCreated - parseJSON (Number 2) = pure FcChanged - parseJSON (Number 3) = pure FcDeleted - parseJSON _ = fail "FileChangetype" - - --- ------------------------------------- - --- | An event describing a file change. -data FileEvent = - FileEvent - { -- | The file's URI. - _uri :: Uri - -- | The change type. - , _xtype :: FileChangeType - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''FileEvent - -data DidChangeWatchedFilesParams = - DidChangeWatchedFilesParams - { -- | The actual file events. - _changes :: List FileEvent - } deriving (Read,Show,Eq) - -deriveJSON lspOptions ''DidChangeWatchedFilesParams diff --git a/lsp-types/src/Language/LSP/Types/Window.hs b/lsp-types/src/Language/LSP/Types/Window.hs deleted file mode 100644 index eeb20862d..000000000 --- a/lsp-types/src/Language/LSP/Types/Window.hs +++ /dev/null @@ -1,114 +0,0 @@ -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.Window where - -import qualified Data.Aeson as A -import Data.Aeson.TH -import Data.Text (Text) -import Language.LSP.Types.Utils -import Language.LSP.Types.Uri -import Language.LSP.Types.Location - --- --------------------------------------------------------------------- - -data MessageType = MtError -- ^ Error = 1, - | MtWarning -- ^ Warning = 2, - | MtInfo -- ^ Info = 3, - | MtLog -- ^ Log = 4 - deriving (Eq,Ord,Show,Read,Enum) - -instance A.ToJSON MessageType where - toJSON MtError = A.Number 1 - toJSON MtWarning = A.Number 2 - toJSON MtInfo = A.Number 3 - toJSON MtLog = A.Number 4 - -instance A.FromJSON MessageType where - parseJSON (A.Number 1) = pure MtError - parseJSON (A.Number 2) = pure MtWarning - parseJSON (A.Number 3) = pure MtInfo - parseJSON (A.Number 4) = pure MtLog - parseJSON _ = fail "MessageType" - --- --------------------------------------- - - -data ShowMessageParams = - ShowMessageParams { - _xtype :: MessageType - , _message :: Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ShowMessageParams - --- --------------------------------------------------------------------- - -data MessageActionItem = - MessageActionItem - { _title :: Text - } deriving (Show,Read,Eq) - -deriveJSON lspOptions ''MessageActionItem - - -data ShowMessageRequestParams = - ShowMessageRequestParams - { _xtype :: MessageType - , _message :: Text - , _actions :: Maybe [MessageActionItem] - } deriving (Show,Read,Eq) - -deriveJSON lspOptions ''ShowMessageRequestParams - --- --------------------------------------------------------------------- - --- | Params to show a document. --- --- @since 3.16.0 -data ShowDocumentParams = - ShowDocumentParams { - -- | The document uri to show. - _uri :: Uri - - -- | Indicates to show the resource in an external program. - -- To show for example `https://code.visualstudio.com/` - -- in the default WEB browser set `external` to `true`. - , _external :: Maybe Bool - - -- | An optional property to indicate whether the editor - -- showing the document should take focus or not. - -- Clients might ignore this property if an external - -- program is started. - , _takeFocus :: Maybe Bool - - -- | An optional selection range if the document is a text - -- document. Clients might ignore the property if an - -- external program is started or the file is not a text - -- file. - , _selection :: Maybe Range - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ShowDocumentParams - --- | The result of an show document request. --- --- @since 3.16.0 -data ShowDocumentResult = - ShowDocumentResult { - -- | A boolean indicating if the show was successful. - _success :: Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ShowDocumentResult - --- --------------------------------------------------------------------- - -data LogMessageParams = - LogMessageParams { - _xtype :: MessageType - , _message :: Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''LogMessageParams diff --git a/lsp-types/src/Language/LSP/Types/WorkspaceEdit.hs b/lsp-types/src/Language/LSP/Types/WorkspaceEdit.hs index ecd01ad9b..a2958ebf1 100644 --- a/lsp-types/src/Language/LSP/Types/WorkspaceEdit.hs +++ b/lsp-types/src/Language/LSP/Types/WorkspaceEdit.hs @@ -1,375 +1,18 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE TypeOperators #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE DuplicateRecordFields #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE TypeOperators #-} module Language.LSP.Types.WorkspaceEdit where -import Control.Monad (unless) -import Data.Aeson -import Data.Aeson.TH -import qualified Data.HashMap.Strict as H -import Data.Maybe (catMaybes) -import Data.Text (Text) -import qualified Data.Text as T -import Data.Hashable +import Data.Text (Text) +import qualified Data.Text as T +import Control.Lens import Language.LSP.Types.Common -import Language.LSP.Types.Location -import Language.LSP.Types.TextDocument -import Language.LSP.Types.Uri -import Language.LSP.Types.Utils +import Language.LSP.Types.Internal.Generated --- --------------------------------------------------------------------- - -data TextEdit = - TextEdit - { _range :: Range - , _newText :: Text - } deriving (Show,Read,Eq) - -deriveJSON lspOptions ''TextEdit - --- --------------------------------------------------------------------- - -{-| -Additional information that describes document changes. - -@since 3.16.0 --} -data ChangeAnnotation = - ChangeAnnotation - { -- | A human-readable string describing the actual change. The string - -- is rendered prominent in the user interface. - _label :: Text - -- | A flag which indicates that user confirmation is needed - -- before applying the change. - , _needsConfirmation :: Maybe Bool - -- | A human-readable string which is rendered less prominent in - -- the user interface. - , _description :: Maybe Text - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ChangeAnnotation - -{-| -An identifier referring to a change annotation managed by a workspace -edit. - -@since 3.16.0 --} -newtype ChangeAnnotationIdentifier = ChangeAnnotationIdentifierId Text - deriving (Show, Read, Eq, FromJSON, ToJSON, ToJSONKey, FromJSONKey, Hashable) - -makeExtendingDatatype "AnnotatedTextEdit" [''TextEdit] - [("_annotationId", [t| ChangeAnnotationIdentifier |]) ] -deriveJSON lspOptions ''AnnotatedTextEdit - --- --------------------------------------------------------------------- - -data TextDocumentEdit = - TextDocumentEdit - { _textDocument :: VersionedTextDocumentIdentifier - , _edits :: List (TextEdit |? AnnotatedTextEdit) - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''TextDocumentEdit - --- --------------------------------------------------------------------- - --- | Options to create a file. -data CreateFileOptions = - CreateFileOptions - { -- | Overwrite existing file. Overwrite wins over `ignoreIfExists` - _overwrite :: Maybe Bool - -- | Ignore if exists. - , _ignoreIfExists :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''CreateFileOptions - --- | Create file operation -data CreateFile = - CreateFile - { -- | The resource to create. - _uri :: Uri - -- | Additional options - , _options :: Maybe CreateFileOptions - -- | An optional annotation identifer describing the operation. - -- - -- @since 3.16.0 - , _annotationId :: Maybe ChangeAnnotationIdentifier - } deriving (Show, Read, Eq) - -instance ToJSON CreateFile where - toJSON CreateFile{..} = - object $ catMaybes - [ Just $ "kind" .= ("create" :: Text) - , Just $ "uri" .= _uri - , ("options" .=) <$> _options - , ("annotationId" .=) <$> _annotationId - ] - -instance FromJSON CreateFile where - parseJSON = withObject "CreateFile" $ \o -> do - kind <- o .: "kind" - unless (kind == ("create" :: Text)) - $ fail $ "Expected kind \"create\" but got " ++ show kind - _uri <- o .: "uri" - _options <- o .:? "options" - _annotationId <- o .:? "annotationId" - pure CreateFile{..} - --- Rename file options -data RenameFileOptions = - RenameFileOptions - { -- | Overwrite target if existing. Overwrite wins over `ignoreIfExists` - _overwrite :: Maybe Bool - -- | Ignores if target exists. - , _ignoreIfExists :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''RenameFileOptions - --- | Rename file operation -data RenameFile = - RenameFile - { -- | The old (existing) location. - _oldUri :: Uri - -- | The new location. - , _newUri :: Uri - -- | Rename options. - , _options :: Maybe RenameFileOptions - -- | An optional annotation identifer describing the operation. - -- - -- @since 3.16.0 - , _annotationId :: Maybe ChangeAnnotationIdentifier - } deriving (Show, Read, Eq) - -instance ToJSON RenameFile where - toJSON RenameFile{..} = - object $ catMaybes - [ Just $ "kind" .= ("rename" :: Text) - , Just $ "oldUri" .= _oldUri - , Just $ "newUri" .= _newUri - , ("options" .=) <$> _options - , ("annotationId" .=) <$> _annotationId - ] - -instance FromJSON RenameFile where - parseJSON = withObject "RenameFile" $ \o -> do - kind <- o .: "kind" - unless (kind == ("rename" :: Text)) - $ fail $ "Expected kind \"rename\" but got " ++ show kind - _oldUri <- o .: "oldUri" - _newUri <- o .: "newUri" - _options <- o .:? "options" - _annotationId <- o .:? "annotationId" - pure RenameFile{..} - --- Delete file options -data DeleteFileOptions = - DeleteFileOptions - { -- | Delete the content recursively if a folder is denoted. - _recursive :: Maybe Bool - -- | Ignore the operation if the file doesn't exist. - , _ignoreIfNotExists :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''DeleteFileOptions - --- | Delete file operation -data DeleteFile = - DeleteFile - { -- | The file to delete. - _uri :: Uri - -- | Delete options. - , _options :: Maybe DeleteFileOptions - -- | An optional annotation identifer describing the operation. - -- - -- @since 3.16.0 - , _annotationId :: Maybe ChangeAnnotationIdentifier - } deriving (Show, Read, Eq) - -instance ToJSON DeleteFile where - toJSON DeleteFile{..} = - object $ catMaybes - [ Just $ "kind" .= ("delete" :: Text) - , Just $ "uri" .= _uri - , ("options" .=) <$> _options - , ("annotationId" .=) <$> _annotationId - ] - -instance FromJSON DeleteFile where - parseJSON = withObject "DeleteFile" $ \o -> do - kind <- o .: "kind" - unless (kind == ("delete" :: Text)) - $ fail $ "Expected kind \"delete\" but got " ++ show kind - _uri <- o .: "uri" - _options <- o .:? "options" - _annotationId <- o .:? "annotationId" - pure DeleteFile{..} - --- --------------------------------------------------------------------- - --- | `TextDocumentEdit |? CreateFile |? RenameFile |? DeleteFile` is a bit mouthful, here's the synonym type DocumentChange = TextDocumentEdit |? CreateFile |? RenameFile |? DeleteFile --- --------------------------------------------------------------------- - -type WorkspaceEditMap = H.HashMap Uri (List TextEdit) -type ChangeAnnotationMap = H.HashMap ChangeAnnotationIdentifier ChangeAnnotation - -data WorkspaceEdit = - WorkspaceEdit - { - -- | Holds changes to existing resources. - _changes :: Maybe WorkspaceEditMap - -- | Depending on the client capability - -- `workspace.workspaceEdit.resourceOperations` document changes are either - -- an array of `TextDocumentEdit`s to express changes to n different text - -- documents where each text document edit addresses a specific version of - -- a text document. Or it can contain above `TextDocumentEdit`s mixed with - -- create, rename and delete file / folder operations. - -- - -- Whether a client supports versioned document edits is expressed via - -- `workspace.workspaceEdit.documentChanges` client capability. - -- - -- If a client neither supports `documentChanges` nor - -- `workspace.workspaceEdit.resourceOperations` then only plain `TextEdit`s - -- using the `changes` property are supported. - , _documentChanges :: Maybe (List DocumentChange) - -- | A map of change annotations that can be referenced in - -- `AnnotatedTextEdit`s or create, rename and delete file / folder - -- operations. - -- - -- Whether clients honor this property depends on the client capability - -- `workspace.changeAnnotationSupport`. - -- - -- @since 3.16.0 - , _changeAnnotations :: Maybe ChangeAnnotationMap - } deriving (Show, Read, Eq) - -instance Semigroup WorkspaceEdit where - (WorkspaceEdit a b c) <> (WorkspaceEdit a' b' c') = WorkspaceEdit (a <> a') (b <> b') (c <> c') -instance Monoid WorkspaceEdit where - mempty = WorkspaceEdit Nothing Nothing Nothing - -deriveJSON lspOptions ''WorkspaceEdit - --- ------------------------------------- - -data ResourceOperationKind - = ResourceOperationCreate -- ^ Supports creating new files and folders. - | ResourceOperationRename -- ^ Supports renaming existing files and folders. - | ResourceOperationDelete -- ^ Supports deleting existing files and folders. - deriving (Read, Show, Eq) - -instance ToJSON ResourceOperationKind where - toJSON ResourceOperationCreate = String "create" - toJSON ResourceOperationRename = String "rename" - toJSON ResourceOperationDelete = String "delete" - -instance FromJSON ResourceOperationKind where - parseJSON (String "create") = pure ResourceOperationCreate - parseJSON (String "rename") = pure ResourceOperationRename - parseJSON (String "delete") = pure ResourceOperationDelete - parseJSON _ = fail "ResourceOperationKind" - -data FailureHandlingKind - = FailureHandlingAbort -- ^ Applying the workspace change is simply aborted if one of the changes provided fails. All operations executed before the failing operation stay executed. - | FailureHandlingTransactional -- ^ All operations are executed transactional. That means they either all succeed or no changes at all are applied to the workspace. - | FailureHandlingTextOnlyTransactional -- ^ If the workspace edit contains only textual file changes they are executed transactional. If resource changes (create, rename or delete file) are part of the change the failure handling strategy is abort. - | FailureHandlingUndo -- ^ The client tries to undo the operations already executed. But there is no guarantee that this is succeeding. - deriving (Read, Show, Eq) - -instance ToJSON FailureHandlingKind where - toJSON FailureHandlingAbort = String "abort" - toJSON FailureHandlingTransactional = String "transactional" - toJSON FailureHandlingTextOnlyTransactional = String "textOnlyTransactional" - toJSON FailureHandlingUndo = String "undo" - -instance FromJSON FailureHandlingKind where - parseJSON (String "abort") = pure FailureHandlingAbort - parseJSON (String "transactional") = pure FailureHandlingTransactional - parseJSON (String "textOnlyTransactional") = pure FailureHandlingTextOnlyTransactional - parseJSON (String "undo") = pure FailureHandlingUndo - parseJSON _ = fail "FailureHandlingKind" - -data WorkspaceEditChangeAnnotationClientCapabilities = - WorkspaceEditChangeAnnotationClientCapabilities - { - -- | Whether the client groups edits with equal labels into tree nodes, - -- for instance all edits labelled with "Changes in Strings" would - -- be a tree node. - groupsOnLabel :: Maybe Bool - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceEditChangeAnnotationClientCapabilities - -data WorkspaceEditClientCapabilities = - WorkspaceEditClientCapabilities - { _documentChanges :: Maybe Bool -- ^The client supports versioned document - -- changes in 'WorkspaceEdit's - -- | The resource operations the client supports. Clients should at least - -- support @create@, @rename@ and @delete@ files and folders. - , _resourceOperations :: Maybe (List ResourceOperationKind) - -- | The failure handling strategy of a client if applying the workspace edit - -- fails. - , _failureHandling :: Maybe FailureHandlingKind - -- | Whether the client normalizes line endings to the client specific - -- setting. - -- - -- If set to `true` the client will normalize line ending characters - -- in a workspace edit to the client specific new line character(s). - -- - -- @since 3.16.0 - , _normalizesLineEndings :: Maybe Bool - -- | Whether the client in general supports change annotations on text edits, - -- create file, rename file and delete file changes. - -- - -- @since 3.16.0 - , _changeAnnotationSupport :: Maybe WorkspaceEditChangeAnnotationClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceEditClientCapabilities - --- --------------------------------------------------------------------- - -data ApplyWorkspaceEditParams = - ApplyWorkspaceEditParams - { -- | An optional label of the workspace edit. This label is - -- presented in the user interface for example on an undo - -- stack to undo the workspace edit. - _label :: Maybe Text - -- | The edits to apply - , _edit :: WorkspaceEdit - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ApplyWorkspaceEditParams - -data ApplyWorkspaceEditResponseBody = - ApplyWorkspaceEditResponseBody - { -- | Indicates whether the edit was applied or not. - _applied :: Bool - -- | An optional textual description for why the edit was not applied. - -- This may be used may be used by the server for diagnostic - -- logging or to provide a suitable error for a request that - -- triggered the edit. - , _failureReason :: Maybe Text - -- | Depending on the client's failure handling strategy `failedChange` - -- might contain the index of the change that failed. This property is - -- only available if the client signals a `failureHandling` strategy - -- in its client capabilities. - , _failedChange :: Maybe UInt - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''ApplyWorkspaceEditResponseBody - --- --------------------------------------------------------------------- - -- | Applies a 'TextEdit' to some 'Text'. -- >>> applyTextEdit (TextEdit (Range (Position 0 1) (Position 0 2)) "i") "foo" -- "fio" @@ -402,3 +45,11 @@ editTextEdit :: TextEdit -> TextEdit -> TextEdit editTextEdit (TextEdit origRange origText) innerEdit = let newText = applyTextEdit innerEdit origText in TextEdit origRange newText + +-- | Conversion between 'OptionalVersionedTextDocumentIdentifier' and 'VersionedTextDocumentIdentifier'. +_versionedTextDocumentIdentifier :: Prism' OptionalVersionedTextDocumentIdentifier VersionedTextDocumentIdentifier +_versionedTextDocumentIdentifier = prism down up + where + down (VersionedTextDocumentIdentifier uri v) = OptionalVersionedTextDocumentIdentifier uri (InL v) + up (OptionalVersionedTextDocumentIdentifier uri (InL v)) = Right $ VersionedTextDocumentIdentifier uri v + up i@(OptionalVersionedTextDocumentIdentifier _ (InR _)) = Left i diff --git a/lsp-types/src/Language/LSP/Types/WorkspaceFolders.hs b/lsp-types/src/Language/LSP/Types/WorkspaceFolders.hs deleted file mode 100644 index faee28fd2..000000000 --- a/lsp-types/src/Language/LSP/Types/WorkspaceFolders.hs +++ /dev/null @@ -1,37 +0,0 @@ -{-# LANGUAGE DuplicateRecordFields #-} -{-# LANGUAGE TemplateHaskell #-} -module Language.LSP.Types.WorkspaceFolders where - -import Data.Aeson.TH -import Data.Text ( Text ) - -import Language.LSP.Types.Common -import Language.LSP.Types.Utils - -data WorkspaceFolder = - WorkspaceFolder - { -- | The URI of the workspace folder. - _uri :: Text - -- | The name of the workspace folder. Defaults to the uri's basename. - , _name :: Text - } deriving (Read, Show, Eq) - -deriveJSON lspOptions ''WorkspaceFolder - --- | The workspace folder change event. -data WorkspaceFoldersChangeEvent = - WorkspaceFoldersChangeEvent - { _added :: List WorkspaceFolder -- ^ The array of added workspace folders - , _removed :: List WorkspaceFolder -- ^ The array of the removed workspace folders - } deriving (Read, Show, Eq) - -deriveJSON lspOptions ''WorkspaceFoldersChangeEvent - -data DidChangeWorkspaceFoldersParams = - DidChangeWorkspaceFoldersParams - { _event :: WorkspaceFoldersChangeEvent - -- ^ The actual workspace folder change event. - } deriving (Read, Show, Eq) - -deriveJSON lspOptions ''DidChangeWorkspaceFoldersParams - diff --git a/lsp-types/src/Language/LSP/Types/WorkspaceSymbol.hs b/lsp-types/src/Language/LSP/Types/WorkspaceSymbol.hs deleted file mode 100644 index 6ee360483..000000000 --- a/lsp-types/src/Language/LSP/Types/WorkspaceSymbol.hs +++ /dev/null @@ -1,91 +0,0 @@ -{-# LANGUAGE TemplateHaskell #-} -{-# LANGUAGE DuplicateRecordFields #-} - -module Language.LSP.Types.WorkspaceSymbol where - -import Data.Aeson.TH -import Data.Default -import Language.LSP.Types.Common -import Language.LSP.Types.DocumentSymbol -import Language.LSP.Types.Progress -import Language.LSP.Types.Utils -import Data.Text (Text) - -data WorkspaceSymbolKindClientCapabilities = - WorkspaceSymbolKindClientCapabilities - { -- | The symbol kind values the client supports. When this - -- property exists the client also guarantees that it will - -- handle values outside its set gracefully and falls back - -- to a default value when unknown. - -- - -- If this property is not present the client only supports - -- the symbol kinds from `File` to `Array` as defined in - -- the initial version of the protocol. - _valueSet :: Maybe (List SymbolKind) - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceSymbolKindClientCapabilities - -data WorkspaceSymbolTagClientCapabilities = - WorkspaceSymbolTagClientCapabilities - { -- | The tags supported by the client. - _valueSet :: Maybe (List SymbolTag) - } - deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceSymbolTagClientCapabilities - -instance Default WorkspaceSymbolKindClientCapabilities where - def = WorkspaceSymbolKindClientCapabilities (Just $ List allKinds) - where allKinds = [ SkFile - , SkModule - , SkNamespace - , SkPackage - , SkClass - , SkMethod - , SkProperty - , SkField - , SkConstructor - , SkEnum - , SkInterface - , SkFunction - , SkVariable - , SkConstant - , SkString - , SkNumber - , SkBoolean - , SkArray - ] - -data WorkspaceSymbolClientCapabilities = - WorkspaceSymbolClientCapabilities - { _dynamicRegistration :: Maybe Bool -- ^Symbol request supports dynamic - -- registration. - , _symbolKind :: Maybe WorkspaceSymbolKindClientCapabilities -- ^ Specific capabilities for the `SymbolKind`. - -- | The client supports tags on `SymbolInformation`. - -- Clients supporting tags have to handle unknown tags gracefully. - -- - -- @since 3.16.0 - , _tagSupport :: Maybe WorkspaceSymbolTagClientCapabilities - } deriving (Show, Read, Eq) - -deriveJSON lspOptions ''WorkspaceSymbolClientCapabilities - --- ------------------------------------- - -makeExtendingDatatype "WorkspaceSymbolOptions" [''WorkDoneProgressOptions] [] -deriveJSON lspOptions ''WorkspaceSymbolOptions - -makeExtendingDatatype "WorkspaceSymbolRegistrationOptions" - [''WorkspaceSymbolOptions] [] -deriveJSON lspOptions ''WorkspaceSymbolRegistrationOptions - --- ------------------------------------- - -makeExtendingDatatype "WorkspaceSymbolParams" - [ ''WorkDoneProgressParams - , ''PartialResultParams - ] - [("_query", [t| Text |])] - -deriveJSON lspOptions ''WorkspaceSymbolParams diff --git a/lsp-types/test/CapabilitiesSpec.hs b/lsp-types/test/CapabilitiesSpec.hs index a91e23019..b481e1033 100644 --- a/lsp-types/test/CapabilitiesSpec.hs +++ b/lsp-types/test/CapabilitiesSpec.hs @@ -1,16 +1,17 @@ +{-# LANGUAGE DuplicateRecordFields #-} module CapabilitiesSpec where -import Language.LSP.Types -import Language.LSP.Types.Capabilities -import Test.Hspec +import Language.LSP.Types +import Language.LSP.Types.Capabilities +import Test.Hspec spec :: Spec spec = describe "capabilities" $ do it "gives 3.10 capabilities" $ - let ClientCapabilities _ (Just tdcs) _ _ _ = capsForVersion (LSPVersion 3 10) - Just (DocumentSymbolClientCapabilities _ _ mHierarchical _ _ ) = _documentSymbol tdcs + let ClientCapabilities{_textDocument=Just tdcs} = capsForVersion (LSPVersion 3 10) + Just (DocumentSymbolClientCapabilities{_hierarchicalDocumentSymbolSupport=mHierarchical}) = _documentSymbol tdcs in mHierarchical `shouldBe` Just True it "gives pre 3.10 capabilities" $ - let ClientCapabilities _ (Just tdcs) _ _ _ = capsForVersion (LSPVersion 3 9) - Just (DocumentSymbolClientCapabilities _ _ mHierarchical _ _) = _documentSymbol tdcs + let ClientCapabilities{_textDocument=Just tdcs} = capsForVersion (LSPVersion 3 9) + Just (DocumentSymbolClientCapabilities{_hierarchicalDocumentSymbolSupport=mHierarchical}) = _documentSymbol tdcs in mHierarchical `shouldBe` Nothing diff --git a/lsp-types/test/JsonSpec.hs b/lsp-types/test/JsonSpec.hs index 8e57708c0..8812c159e 100644 --- a/lsp-types/test/JsonSpec.hs +++ b/lsp-types/test/JsonSpec.hs @@ -1,23 +1,31 @@ -{-# LANGUAGE UndecidableInstances #-} -{-# LANGUAGE FlexibleContexts #-} -{-# LANGUAGE TypeInType #-} -{-# LANGUAGE FlexibleInstances #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeInType #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE TypeOperators #-} + {-# OPTIONS_GHC -fno-warn-orphans #-} --- For the use of MarkedString -{-# OPTIONS_GHC -fno-warn-deprecations #-} -- | Test for JSON serialization module JsonSpec where import Language.LSP.Types -import qualified Data.Aeson as J -import Data.List(isPrefixOf) +import qualified Data.Aeson as J +import Data.List (isPrefixOf) +import qualified Data.Row as R +import qualified Data.Row.Records as R +import Data.Void import Test.Hspec import Test.Hspec.QuickCheck -import Test.QuickCheck hiding (Success) -import Test.QuickCheck.Instances () +import Test.QuickCheck hiding (Success) +import Test.QuickCheck.Instances () -- import Debug.Trace -- --------------------------------------------------------------------- @@ -38,19 +46,16 @@ jsonSpec :: Spec jsonSpec = do describe "General JSON instances round trip" $ do -- DataTypesJSON - prop "LanguageString" (propertyJsonRoundtrip :: LanguageString -> Property) prop "MarkedString" (propertyJsonRoundtrip :: MarkedString -> Property) prop "MarkupContent" (propertyJsonRoundtrip :: MarkupContent -> Property) - prop "HoverContents" (propertyJsonRoundtrip :: HoverContents -> Property) - prop "ResponseError" (propertyJsonRoundtrip :: ResponseError -> Property) prop "WatchedFiles" (propertyJsonRoundtrip :: DidChangeWatchedFilesRegistrationOptions -> Property) - prop "ResponseMessage Initialize" - (propertyJsonRoundtrip :: ResponseMessage 'TextDocumentHover -> Property) + prop "ResponseMessage Hover" + (propertyJsonRoundtrip :: TResponseMessage 'Method_TextDocumentHover -> Property) -- prop "ResponseMessage JSON value" -- (propertyJsonRoundtrip :: ResponseMessage J.Value -> Property) describe "JSON decoding regressions" $ it "CompletionItem" $ - (J.decode "{\"jsonrpc\":\"2.0\",\"result\":[{\"label\":\"raisebox\"}],\"id\":1}" :: Maybe (ResponseMessage 'TextDocumentCompletion)) + (J.decode "{\"jsonrpc\":\"2.0\",\"result\":[{\"label\":\"raisebox\"}],\"id\":1}" :: Maybe (TResponseMessage 'Method_TextDocumentCompletion)) `shouldNotBe` Nothing @@ -60,18 +65,18 @@ responseMessageSpec = do it "decodes result = null" $ do let input = "{\"jsonrpc\": \"2.0\", \"id\": 123, \"result\": null}" in J.decode input `shouldBe` Just - ((ResponseMessage "2.0" (Just (IdInt 123)) (Right J.Null)) :: ResponseMessage 'WorkspaceExecuteCommand) + ((TResponseMessage "2.0" (Just (IdInt 123)) (Right $ InR Null)) :: TResponseMessage 'Method_WorkspaceExecuteCommand) it "handles missing params field" $ do J.eitherDecode "{ \"jsonrpc\": \"2.0\", \"id\": 15, \"method\": \"shutdown\"}" - `shouldBe` Right (RequestMessage "2.0" (IdInt 15) SShutdown Empty) + `shouldBe` Right (TRequestMessage "2.0" (IdInt 15) SMethod_Shutdown Nothing) describe "invalid JSON" $ do it "throws if neither result nor error is present" $ do - (J.eitherDecode "{\"jsonrpc\":\"2.0\",\"id\":1}" :: Either String (ResponseMessage 'Initialize)) + (J.eitherDecode "{\"jsonrpc\":\"2.0\",\"id\":1}" :: Either String (TResponseMessage 'Method_Initialize)) `shouldBe` Left ("Error in $: both error and result cannot be Nothing") it "throws if both result and error are present" $ do (J.eitherDecode - "{\"jsonrpc\":\"2.0\",\"id\": 1,\"result\":{\"capabilities\": {}},\"error\":{\"code\":-32700,\"message\":\"\",\"data\":null}}" - :: Either String (ResponseMessage 'Initialize)) + "{\"jsonrpc\":\"2.0\",\"id\": 1,\"result\":{\"capabilities\": {}},\"error\":{\"code\":-32700,\"message\":\"\",\"data\":{ \"retry\":false}}}" + :: Either String (TResponseMessage 'Method_Initialize)) `shouldSatisfy` (either (\err -> "Error in $: both error and result cannot be present" `isPrefixOf` err) (\_ -> False)) @@ -82,22 +87,22 @@ propertyJsonRoundtrip a = J.Success a === J.fromJSON (J.toJSON a) -- --------------------------------------------------------------------- -instance Arbitrary LanguageString where - arbitrary = LanguageString <$> arbitrary <*> arbitrary +instance (Arbitrary a, Arbitrary b) => Arbitrary (a |? b) where + arbitrary = oneof [InL <$> arbitrary, InR <$> arbitrary] + +instance Arbitrary Null where + arbitrary = pure Null -instance Arbitrary MarkedString where - arbitrary = oneof [PlainString <$> arbitrary, CodeString <$> arbitrary] +instance (R.AllUniqueLabels r, R.Forall r Arbitrary) => Arbitrary (R.Rec r) where + arbitrary = R.fromLabelsA @Arbitrary $ \_l -> arbitrary + +deriving newtype instance Arbitrary MarkedString instance Arbitrary MarkupContent where arbitrary = MarkupContent <$> arbitrary <*> arbitrary instance Arbitrary MarkupKind where - arbitrary = oneof [pure MkPlainText,pure MkMarkdown] - -instance Arbitrary HoverContents where - arbitrary = oneof [ HoverContentsMS <$> arbitrary - , HoverContents <$> arbitrary - ] + arbitrary = oneof [pure MarkupKind_PlainText,pure MarkupKind_Markdown] instance Arbitrary UInt where arbitrary = fromInteger <$> arbitrary @@ -105,6 +110,17 @@ instance Arbitrary UInt where instance Arbitrary Uri where arbitrary = Uri <$> arbitrary +--deriving newtype instance Arbitrary URI + +instance Arbitrary WorkspaceFolder where + arbitrary = WorkspaceFolder <$> arbitrary <*> arbitrary + +instance Arbitrary RelativePattern where + arbitrary = RelativePattern <$> arbitrary <*> arbitrary + +deriving newtype instance Arbitrary Pattern +deriving newtype instance Arbitrary GlobPattern + instance Arbitrary Position where arbitrary = Position <$> arbitrary <*> arbitrary @@ -117,48 +133,33 @@ instance Arbitrary Range where instance Arbitrary Hover where arbitrary = Hover <$> arbitrary <*> arbitrary -instance Arbitrary (ResponseResult m) => Arbitrary (ResponseMessage m) where - arbitrary = - oneof - [ ResponseMessage - <$> arbitrary - <*> arbitrary - <*> (Right <$> arbitrary) - , ResponseMessage - <$> arbitrary - <*> arbitrary - <*> (Left <$> arbitrary) - ] +instance {-# OVERLAPPING #-} Arbitrary (Maybe Void) where + arbitrary = pure Nothing + +instance (ErrorData m ~ Maybe Void) => Arbitrary (TResponseError m) where + arbitrary = TResponseError <$> arbitrary <*> arbitrary <*> pure Nothing + +instance (Arbitrary (MessageResult m), ErrorData m ~ Maybe Void) => Arbitrary (TResponseMessage m) where + arbitrary = TResponseMessage <$> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary (LspId m) where arbitrary = oneof [IdInt <$> arbitrary, IdString <$> arbitrary] -instance Arbitrary ResponseError where - arbitrary = ResponseError <$> arbitrary <*> arbitrary <*> pure Nothing - -instance Arbitrary ErrorCode where +instance Arbitrary ErrorCodes where arbitrary = elements - [ ParseError - , InvalidRequest - , MethodNotFound - , InvalidParams - , InternalError - , ServerErrorStart - , ServerErrorEnd - , ServerNotInitialized - , UnknownErrorCode - , RequestCancelled - , ContentModified + [ ErrorCodes_ParseError + , ErrorCodes_InvalidRequest + , ErrorCodes_MethodNotFound + , ErrorCodes_InvalidParams + , ErrorCodes_InternalError + , ErrorCodes_ServerNotInitialized + , ErrorCodes_UnknownErrorCode + -- TODO: LSP error codes don't work properly + --, ErrorCodes_RequestCancelled + --, ErrorCodes_ContentModified ] --- | make lists of maximum length 3 for test performance -smallList :: Gen a -> Gen [a] -smallList = resize 3 . listOf - -instance (Arbitrary a) => Arbitrary (List a) where - arbitrary = List <$> arbitrary - -- --------------------------------------------------------------------- instance Arbitrary DidChangeWatchedFilesRegistrationOptions where @@ -167,7 +168,8 @@ instance Arbitrary DidChangeWatchedFilesRegistrationOptions where instance Arbitrary FileSystemWatcher where arbitrary = FileSystemWatcher <$> arbitrary <*> arbitrary +-- TODO: watchKind is weird instance Arbitrary WatchKind where - arbitrary = WatchKind <$> arbitrary <*> arbitrary <*> arbitrary + arbitrary = oneof [pure WatchKind_Change, pure WatchKind_Create, pure WatchKind_Delete] -- --------------------------------------------------------------------- diff --git a/lsp-types/test/Main.hs b/lsp-types/test/Main.hs index 0dabfb276..bbbfdc372 100644 --- a/lsp-types/test/Main.hs +++ b/lsp-types/test/Main.hs @@ -1,7 +1,7 @@ module Main where -import Test.Hspec.Runner import qualified Spec +import Test.Hspec.Runner main :: IO () main = hspec Spec.spec diff --git a/lsp-types/test/MethodSpec.hs b/lsp-types/test/MethodSpec.hs index 84eb18716..c93c23119 100644 --- a/lsp-types/test/MethodSpec.hs +++ b/lsp-types/test/MethodSpec.hs @@ -1,12 +1,13 @@ -{-# LANGUAGE OverloadedStrings, DataKinds #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedStrings #-} module MethodSpec where import Control.Monad -import qualified Data.Aeson as J -import qualified Language.LSP.Types as J +import qualified Data.Aeson as J +import qualified Data.Text as T +import qualified Language.LSP.Types as J import Test.Hspec -import qualified Data.Text as T -- --------------------------------------------------------------------- @@ -25,7 +26,8 @@ clientMethods = [ ,"initialized" ,"shutdown" ,"exit" - ,"$/cancelRequest" + -- FIXME: messages in both directions are busted + -- ,"$/cancelRequest" -- Workspace ,"workspace/didChangeConfiguration" ,"workspace/didChangeWatchedFiles" @@ -61,7 +63,8 @@ clientMethods = [ ,"callHierarchy/incomingCalls" ,"callHierarchy/outgoingCalls" - ,"textDocument/semanticTokens" + -- FIXME: weird method + -- ,"textDocument/semanticTokens" ,"textDocument/semanticTokens/full" ,"textDocument/semanticTokens/full/delta" ,"textDocument/semanticTokens/range" diff --git a/lsp-types/test/SemanticTokensSpec.hs b/lsp-types/test/SemanticTokensSpec.hs index 89feeb36d..0c01d2894 100644 --- a/lsp-types/test/SemanticTokensSpec.hs +++ b/lsp-types/test/SemanticTokensSpec.hs @@ -1,33 +1,37 @@ {-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE TypeApplications #-} module SemanticTokensSpec where -import Test.Hspec -import Language.LSP.Types -import Data.List (unfoldr) -import Data.Either (isRight) +import Data.Either (isRight) +import Data.List (unfoldr) +import Language.LSP.Types hiding (context) +import Test.Hspec spec :: Spec spec = do - let exampleLegend = SemanticTokensLegend (List [SttProperty, SttType, SttClass]) (List [StmUnknown "private", StmStatic]) + let + allMods = [SemanticTokenModifiers_Abstract, SemanticTokenModifiers_Static] + exampleLegend = SemanticTokensLegend + (fmap semanticTokenTypesToValue [SemanticTokenTypes_Property, SemanticTokenTypes_Type, SemanticTokenTypes_Class]) + (fmap semanticTokenModifiersToValue allMods) exampleTokens1 = [ - SemanticTokenAbsolute 2 5 3 SttProperty [StmUnknown "private", StmStatic] - , SemanticTokenAbsolute 2 10 4 SttType [] - , SemanticTokenAbsolute 5 2 7 SttClass [] + SemanticTokenAbsolute 2 5 3 SemanticTokenTypes_Property allMods + , SemanticTokenAbsolute 2 10 4 SemanticTokenTypes_Type [] + , SemanticTokenAbsolute 5 2 7 SemanticTokenTypes_Class [] ] exampleTokens2 = [ - SemanticTokenAbsolute 3 5 3 SttProperty [StmUnknown "private", StmStatic] - , SemanticTokenAbsolute 3 10 4 SttType [] - , SemanticTokenAbsolute 6 2 7 SttClass [] + SemanticTokenAbsolute 3 5 3 SemanticTokenTypes_Property allMods + , SemanticTokenAbsolute 3 10 4 SemanticTokenTypes_Type [] + , SemanticTokenAbsolute 6 2 7 SemanticTokenTypes_Class [] ] bigNumber :: UInt bigNumber = 100000 bigTokens = - unfoldr (\i -> if i == bigNumber then Nothing else Just (SemanticTokenAbsolute i 1 1 SttType [StmUnknown "private", StmStatic], i+1)) 0 + unfoldr (\i -> if i == bigNumber then Nothing else Just (SemanticTokenAbsolute i 1 1 SemanticTokenTypes_Type allMods, i+1)) 0 -- Relativized version of bigTokens bigTokensRel = - unfoldr (\i -> if i == bigNumber then Nothing else Just (SemanticTokenRelative (if i == 0 then 0 else 1) 1 1 SttType [StmUnknown "private", StmStatic], i+1)) 0 + unfoldr (\i -> if i == bigNumber then Nothing else Just (SemanticTokenRelative (if i == 0 then 0 else 1) 1 1 SemanticTokenTypes_Type allMods, i+1)) 0 -- One more order of magnitude makes diffing more-or-less hang - possibly we need a better diffing algorithm, since this is only ~= 200 tokens at 5 ints per token -- (I checked and it is the diffing that's slow, not turning it into edits) diff --git a/lsp-types/test/ServerCapabilitiesSpec.hs b/lsp-types/test/ServerCapabilitiesSpec.hs index c18e439e9..e8dffdb4d 100644 --- a/lsp-types/test/ServerCapabilitiesSpec.hs +++ b/lsp-types/test/ServerCapabilitiesSpec.hs @@ -1,40 +1,40 @@ +{-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} module ServerCapabilitiesSpec where -import Control.Lens.Operators -import Data.Aeson -import Language.LSP.Types -import Language.LSP.Types.Capabilities -import Language.LSP.Types.Lens -import Test.Hspec +import Control.Lens.Operators +import Data.Aeson hiding (Null) +import Data.Row +import Language.LSP.Types +import Test.Hspec spec :: Spec spec = describe "server capabilities" $ do describe "folding range options" $ do describe "decodes" $ do it "just id" $ - let input = "{\"id\": \"abc123\"}" - in decode input `shouldBe` Just (FoldingRangeRegistrationOptions Nothing Nothing (Just "abc123")) + let input = "{\"id\": \"abc123\", \"documentSelector\": null}" + in decode input `shouldBe` Just (FoldingRangeRegistrationOptions (InR Null) Nothing (Just "abc123")) it "id and document selector" $ let input = "{\"id\": \"foo\", \"documentSelector\": " <> documentFiltersJson <> "}" - in decode input `shouldBe` Just (FoldingRangeRegistrationOptions (Just documentFilters) Nothing (Just "foo")) + in decode input `shouldBe` Just (FoldingRangeRegistrationOptions (InL documentFilters) Nothing (Just "foo")) it "static boolean" $ let input = "true" in decode input `shouldBe` Just True describe "encodes" $ it "just id" $ - encode (FoldingRangeRegistrationOptions Nothing Nothing (Just "foo")) `shouldBe` "{\"id\":\"foo\"}" + encode (FoldingRangeRegistrationOptions (InR Null) Nothing (Just "foo")) `shouldBe` "{\"documentSelector\":null,\"id\":\"foo\"}" it "decodes" $ let input = "{\"hoverProvider\": true, \"colorProvider\": {\"id\": \"abc123\", \"documentSelector\": " <> documentFiltersJson <> "}}" Just caps = decode input :: Maybe ServerCapabilities - in caps ^. colorProvider `shouldBe` Just (InR $ InR $ DocumentColorRegistrationOptions (Just documentFilters) (Just "abc123") Nothing) + in caps ^. colorProvider `shouldBe` Just (InR $ InR $ DocumentColorRegistrationOptions (InL documentFilters) Nothing (Just "abc123")) describe "client/registerCapability" $ it "allows empty registerOptions" $ let input = "{\"registrations\":[{\"registerOptions\":{},\"method\":\"workspace/didChangeConfiguration\",\"id\":\"4a56f5ca-7188-4f4c-a366-652d6f9d63aa\"}]}" Just registrationParams = decode input :: Maybe RegistrationParams in registrationParams ^. registrations `shouldBe` - List [SomeRegistration $ Registration "4a56f5ca-7188-4f4c-a366-652d6f9d63aa" - SWorkspaceDidChangeConfiguration (Just Empty)] + [toUntypedRegistration $ TRegistration "4a56f5ca-7188-4f4c-a366-652d6f9d63aa" + SMethod_WorkspaceDidChangeConfiguration (Just $ DidChangeConfigurationRegistrationOptions Nothing)] where - documentFilters = List [DocumentFilter (Just "haskell") Nothing Nothing] + documentFilters = DocumentSelector [DocumentFilter $ InL $ TextDocumentFilter $ InL $ #language .== "haskell" .+ #scheme .== Nothing .+ #pattern .== Nothing] documentFiltersJson = "[{\"language\": \"haskell\"}]" diff --git a/lsp-types/test/TypesSpec.hs b/lsp-types/test/TypesSpec.hs index b34d209ad..8eb14d735 100644 --- a/lsp-types/test/TypesSpec.hs +++ b/lsp-types/test/TypesSpec.hs @@ -22,9 +22,9 @@ diagnosticsSpec = do `shouldBe` J.unmarkedUpContent "string1\nstring2\n" it "appends a marked up and a plain string" $ do J.markedUpContent "haskell" "foo :: Int" <> J.unmarkedUpContent "string2\nstring3\n" - `shouldBe` J.MarkupContent J.MkMarkdown "\n```haskell\nfoo :: Int\n```\nstring2 \nstring3 \n" + `shouldBe` J.MarkupContent J.MarkupKind_Markdown "\n```haskell\nfoo :: Int\n```\nstring2 \nstring3 \n" it "appends a plain string and a marked up string" $ do J.unmarkedUpContent "string2\n" <> J.markedUpContent "haskell" "foo :: Int" - `shouldBe` J.MarkupContent J.MkMarkdown "string2 \n\n```haskell\nfoo :: Int\n```\n" + `shouldBe` J.MarkupContent J.MarkupKind_Markdown "string2 \n\n```haskell\nfoo :: Int\n```\n" -- --------------------------------------------------------------------- diff --git a/lsp-types/test/WorkspaceEditSpec.hs b/lsp-types/test/WorkspaceEditSpec.hs index 6779ecc3e..99cba89dc 100644 --- a/lsp-types/test/WorkspaceEditSpec.hs +++ b/lsp-types/test/WorkspaceEditSpec.hs @@ -1,8 +1,8 @@ {-# LANGUAGE OverloadedStrings #-} module WorkspaceEditSpec where -import Test.Hspec -import Language.LSP.Types +import Language.LSP.Types +import Test.Hspec spec :: Spec spec = do diff --git a/lsp/example/Reactor.hs b/lsp/example/Reactor.hs index 28d69c433..3dc08d509 100644 --- a/lsp/example/Reactor.hs +++ b/lsp/example/Reactor.hs @@ -45,8 +45,7 @@ import Language.LSP.Server import System.IO import Language.LSP.Diagnostics import Language.LSP.Logging (defaultClientLogger) -import qualified Language.LSP.Types as J -import qualified Language.LSP.Types.Lens as J +import qualified Language.LSP.Types as LSP import Language.LSP.VFS import System.Exit import Control.Concurrent @@ -119,19 +118,19 @@ run = flip E.catches handlers $ do -- --------------------------------------------------------------------- -syncOptions :: J.TextDocumentSyncOptions -syncOptions = J.TextDocumentSyncOptions - { J._openClose = Just True - , J._change = Just J.TdSyncIncremental - , J._willSave = Just False - , J._willSaveWaitUntil = Just False - , J._save = Just $ J.InR $ J.SaveOptions $ Just False +syncOptions :: LSP.TextDocumentSyncOptions +syncOptions = LSP.TextDocumentSyncOptions + { LSP._openClose = Just True + , LSP._change = Just LSP.TextDocumentSyncKind_Incremental + , LSP._willSave = Just False + , LSP._willSaveWaitUntil = Just False + , LSP._save = Just $ LSP.InR $ LSP.SaveOptions $ Just False } lspOptions :: Options lspOptions = defaultOptions - { textDocumentSync = Just syncOptions - , executeCommandCommands = Just ["lsp-hello-command"] + { optTextDocumentSync = Just syncOptions + , optExecuteCommandCommands = Just ["lsp-hello-command"] } -- --------------------------------------------------------------------- @@ -145,17 +144,19 @@ newtype ReactorInput -- | Analyze the file and send any diagnostics to the client in a -- "textDocument/publishDiagnostics" notification -sendDiagnostics :: J.NormalizedUri -> Maybe Int32 -> LspM Config () +sendDiagnostics :: LSP.NormalizedUri -> Maybe Int32 -> LspM Config () sendDiagnostics fileUri version = do let - diags = [J.Diagnostic - (J.Range (J.Position 0 1) (J.Position 0 5)) - (Just J.DsWarning) -- severity + diags = [LSP.Diagnostic + (LSP.Range (LSP.Position 0 1) (LSP.Position 0 5)) + (Just LSP.DiagnosticSeverity_Warning) -- severity Nothing -- code + Nothing (Just "lsp-hello") -- source "Example diagnostic message" Nothing -- tags - (Just (J.List [])) + (Just []) + Nothing ] publishDiagnostics 100 fileUri version (partitionBySource diags) @@ -176,12 +177,12 @@ reactor logger inp = do lspHandlers :: (m ~ LspM Config) => L.LogAction m (WithSeverity T.Text) -> TChan ReactorInput -> Handlers m lspHandlers logger rin = mapHandlers goReq goNot (handle logger) where - goReq :: forall (a :: J.Method J.FromClient J.Request). Handler (LspM Config) a -> Handler (LspM Config) a + goReq :: forall (a :: LSP.Method LSP.ClientToServer LSP.Request). Handler (LspM Config) a -> Handler (LspM Config) a goReq f = \msg k -> do env <- getLspEnv liftIO $ atomically $ writeTChan rin $ ReactorAction (runLspT env $ f msg k) - goNot :: forall (a :: J.Method J.FromClient J.Notification). Handler (LspM Config) a -> Handler (LspM Config) a + goNot :: forall (a :: LSP.Method LSP.ClientToServer LSP.Notification). Handler (LspM Config) a -> Handler (LspM Config) a goNot f = \msg -> do env <- getLspEnv liftIO $ atomically $ writeTChan rin $ ReactorAction (runLspT env $ f msg) @@ -189,49 +190,49 @@ lspHandlers logger rin = mapHandlers goReq goNot (handle logger) -- | Where the actual logic resides for handling requests and notifications. handle :: (m ~ LspM Config) => L.LogAction m (WithSeverity T.Text) -> Handlers m handle logger = mconcat - [ notificationHandler J.SInitialized $ \_msg -> do + [ notificationHandler LSP.SMethod_Initialized $ \_msg -> do logger <& "Processing the Initialized notification" `WithSeverity` Info -- We're initialized! Lets send a showMessageRequest now - let params = J.ShowMessageRequestParams - J.MtWarning + let params = LSP.ShowMessageRequestParams + LSP.MessageType_Warning "What's your favourite language extension?" - (Just [J.MessageActionItem "Rank2Types", J.MessageActionItem "NPlusKPatterns"]) + (Just [LSP.MessageActionItem "Rank2Types", LSP.MessageActionItem "NPlusKPatterns"]) - void $ sendRequest J.SWindowShowMessageRequest params $ \res -> + void $ sendRequest LSP.SMethod_WindowShowMessageRequest params $ \res -> case res of Left e -> logger <& ("Got an error: " <> T.pack (show e)) `WithSeverity` Error Right _ -> do - sendNotification J.SWindowShowMessage (J.ShowMessageParams J.MtInfo "Excellent choice") + sendNotification LSP.SMethod_WindowShowMessage (LSP.ShowMessageParams LSP.MessageType_Info "Excellent choice") -- We can dynamically register a capability once the user accepts it - sendNotification J.SWindowShowMessage (J.ShowMessageParams J.MtInfo "Turning on code lenses dynamically") + sendNotification LSP.SMethod_WindowShowMessage (LSP.ShowMessageParams LSP.MessageType_Info "Turning on code lenses dynamically") - let regOpts = J.CodeLensRegistrationOptions Nothing Nothing (Just False) + let regOpts = LSP.CodeLensRegistrationOptions (LSP.InR LSP.Null) Nothing (Just False) - void $ registerCapability J.STextDocumentCodeLens regOpts $ \_req responder -> do + void $ registerCapability LSP.SMethod_TextDocumentCodeLens regOpts $ \_req responder -> do logger <& "Processing a textDocument/codeLens request" `WithSeverity` Info - let cmd = J.Command "Say hello" "lsp-hello-command" Nothing - rsp = J.List [J.CodeLens (J.mkRange 0 0 0 100) (Just cmd) Nothing] - responder (Right rsp) + let cmd = LSP.Command "Say hello" "lsp-hello-command" Nothing + rsp = [LSP.CodeLens (LSP.mkRange 0 0 0 100) (Just cmd) Nothing] + responder (Right $ LSP.InL rsp) - , notificationHandler J.STextDocumentDidOpen $ \msg -> do - let doc = msg ^. J.params . J.textDocument . J.uri - fileName = J.uriToFilePath doc + , notificationHandler LSP.SMethod_TextDocumentDidOpen $ \msg -> do + let doc = msg ^. LSP.params . LSP.textDocument . LSP.uri + fileName = LSP.uriToFilePath doc logger <& ("Processing DidOpenTextDocument for: " <> T.pack (show fileName)) `WithSeverity` Info - sendDiagnostics (J.toNormalizedUri doc) (Just 0) + sendDiagnostics (LSP.toNormalizedUri doc) (Just 0) - , notificationHandler J.SWorkspaceDidChangeConfiguration $ \msg -> do + , notificationHandler LSP.SMethod_WorkspaceDidChangeConfiguration $ \msg -> do cfg <- getConfig logger L.<& ("Configuration changed: " <> T.pack (show (msg,cfg))) `WithSeverity` Info - sendNotification J.SWindowShowMessage $ - J.ShowMessageParams J.MtInfo $ "Wibble factor set to " <> T.pack (show (wibbleFactor cfg)) - - , notificationHandler J.STextDocumentDidChange $ \msg -> do - let doc = msg ^. J.params - . J.textDocument - . J.uri - . to J.toNormalizedUri + sendNotification LSP.SMethod_WindowShowMessage $ + LSP.ShowMessageParams LSP.MessageType_Info $ "Wibble factor set to " <> T.pack (show (wibbleFactor cfg)) + + , notificationHandler LSP.SMethod_TextDocumentDidChange $ \msg -> do + let doc = msg ^. LSP.params + . LSP.textDocument + . LSP.uri + . to LSP.toNormalizedUri logger <& ("Processing DidChangeTextDocument for: " <> T.pack (show doc)) `WithSeverity` Info mdoc <- getVirtualFile doc case mdoc of @@ -240,73 +241,72 @@ handle logger = mconcat Nothing -> do logger <& ("Didn't find anything in the VFS for: " <> T.pack (show doc)) `WithSeverity` Info - , notificationHandler J.STextDocumentDidSave $ \msg -> do - let doc = msg ^. J.params . J.textDocument . J.uri - fileName = J.uriToFilePath doc + , notificationHandler LSP.SMethod_TextDocumentDidSave $ \msg -> do + let doc = msg ^. LSP.params . LSP.textDocument . LSP.uri + fileName = LSP.uriToFilePath doc logger <& ("Processing DidSaveTextDocument for: " <> T.pack (show fileName)) `WithSeverity` Info - sendDiagnostics (J.toNormalizedUri doc) Nothing + sendDiagnostics (LSP.toNormalizedUri doc) Nothing - , requestHandler J.STextDocumentRename $ \req responder -> do + , requestHandler LSP.SMethod_TextDocumentRename $ \req responder -> do logger <& "Processing a textDocument/rename request" `WithSeverity` Info - let params = req ^. J.params - J.Position l c = params ^. J.position - newName = params ^. J.newName - vdoc <- getVersionedTextDoc (params ^. J.textDocument) + let params = req ^. LSP.params + LSP.Position l c = params ^. LSP.position + newName = params ^. LSP.newName + vdoc <- getVersionedTextDoc (params ^. LSP.textDocument) -- Replace some text at the position with what the user entered - let edit = J.InL $ J.TextEdit (J.mkRange l c l (c + fromIntegral (T.length newName))) newName - tde = J.TextDocumentEdit vdoc (J.List [edit]) + let edit = LSP.InL $ LSP.TextEdit (LSP.mkRange l c l (c + fromIntegral (T.length newName))) newName + tde = LSP.TextDocumentEdit (LSP._versionedTextDocumentIdentifier # vdoc) [edit] -- "documentChanges" field is preferred over "changes" - rsp = J.WorkspaceEdit Nothing (Just (J.List [J.InL tde])) Nothing - responder (Right rsp) + rsp = LSP.WorkspaceEdit Nothing (Just [LSP.InL tde]) Nothing + responder (Right $ LSP.InL rsp) - , requestHandler J.STextDocumentHover $ \req responder -> do + , requestHandler LSP.SMethod_TextDocumentHover $ \req responder -> do logger <& "Processing a textDocument/hover request" `WithSeverity` Info - let J.HoverParams _doc pos _workDone = req ^. J.params - J.Position _l _c' = pos - rsp = J.Hover ms (Just range) - ms = J.HoverContents $ J.markedUpContent "lsp-hello" "Your type info here!" - range = J.Range pos pos - responder (Right $ Just rsp) - - , requestHandler J.STextDocumentDocumentSymbol $ \req responder -> do + let LSP.HoverParams _doc pos _workDone = req ^. LSP.params + LSP.Position _l _c' = pos + rsp = LSP.Hover ms (Just range) + ms = LSP.InL $ LSP.markedUpContent "lsp-hello" "Your type info here!" + range = LSP.Range pos pos + responder (Right $ LSP.InL rsp) + + , requestHandler LSP.SMethod_TextDocumentDocumentSymbol $ \req responder -> do logger <& "Processing a textDocument/documentSymbol request" `WithSeverity` Info - let J.DocumentSymbolParams _ _ doc = req ^. J.params - loc = J.Location (doc ^. J.uri) (J.Range (J.Position 0 0) (J.Position 0 0)) - sym = J.SymbolInformation "lsp-hello" J.SkFunction Nothing Nothing loc Nothing - rsp = J.InR (J.List [sym]) - responder (Right rsp) + let LSP.DocumentSymbolParams _ _ doc = req ^. LSP.params + loc = LSP.Location (doc ^. LSP.uri) (LSP.Range (LSP.Position 0 0) (LSP.Position 0 0)) + rsp = [LSP.SymbolInformation "lsp-hello" LSP.SymbolKind_Function Nothing Nothing Nothing loc] + responder (Right $ LSP.InL rsp) - , requestHandler J.STextDocumentCodeAction $ \req responder -> do + , requestHandler LSP.SMethod_TextDocumentCodeAction $ \req responder -> do logger <& "Processing a textDocument/codeAction request" `WithSeverity` Info - let params = req ^. J.params - doc = params ^. J.textDocument - (J.List diags) = params ^. J.context . J.diagnostics + let params = req ^. LSP.params + doc = params ^. LSP.textDocument + diags = params ^. LSP.context . LSP.diagnostics -- makeCommand only generates commands for diagnostics whose source is us - makeCommand (J.Diagnostic (J.Range s _) _s _c (Just "lsp-hello") _m _t _l) = [J.Command title cmd cmdparams] - where - title = "Apply LSP hello command:" <> head (T.lines _m) + makeCommand d | (LSP.Range s _) <- d ^. LSP.range, (Just "lsp-hello") <- d ^. LSP.source = + let + title = "Apply LSP hello command:" <> head (T.lines $ d ^. LSP.message) -- NOTE: the cmd needs to be registered via the InitializeResponse message. See lspOptions above cmd = "lsp-hello-command" -- need 'file' and 'start_pos' - args = J.List - [ J.object [("file", J.object [("textDocument",J.toJSON doc)])] - , J.object [("start_pos",J.object [("position", J.toJSON s)])] - ] + args = [ J.object [("file", J.object [("textDocument",J.toJSON doc)])] + , J.object [("start_pos",J.object [("position", J.toJSON s)])] + ] cmdparams = Just args - makeCommand (J.Diagnostic _r _s _c _source _m _t _l) = [] - rsp = J.List $ map J.InL $ concatMap makeCommand diags - responder (Right rsp) + in [LSP.Command title cmd cmdparams] + makeCommand _ = [] + rsp = map LSP.InL $ concatMap makeCommand diags + responder (Right $ LSP.InL rsp) - , requestHandler J.SWorkspaceExecuteCommand $ \req responder -> do + , requestHandler LSP.SMethod_WorkspaceExecuteCommand $ \req responder -> do logger <& "Processing a workspace/executeCommand request" `WithSeverity` Info - let params = req ^. J.params - margs = params ^. J.arguments + let params = req ^. LSP.params + margs = params ^. LSP.arguments logger <& ("The arguments are: " <> T.pack (show margs)) `WithSeverity` Debug - responder (Right (J.Object mempty)) -- respond to the request + responder (Right $ LSP.InL (J.Object mempty)) -- respond to the request void $ withProgress "Executing some long running command" Cancellable $ \update -> - forM [(0 :: J.UInt)..10] $ \i -> do + forM [(0 :: LSP.UInt)..10] $ \i -> do update (ProgressAmount (Just (i * 10)) (Just "Doing stuff")) liftIO $ threadDelay (1 * 1000000) ] diff --git a/lsp/example/Simple.hs b/lsp/example/Simple.hs index f05eac06f..807379f7b 100644 --- a/lsp/example/Simple.hs +++ b/lsp/example/Simple.hs @@ -1,5 +1,6 @@ {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} +{-# LANGUAGE DuplicateRecordFields #-} import Language.LSP.Server import Language.LSP.Types @@ -8,30 +9,30 @@ import qualified Data.Text as T handlers :: Handlers (LspM ()) handlers = mconcat - [ notificationHandler SInitialized $ \_not -> do - let params = ShowMessageRequestParams MtInfo "Turn on code lenses?" + [ notificationHandler SMethod_Initialized $ \_not -> do + let params = ShowMessageRequestParams MessageType_Info "Turn on code lenses?" (Just [MessageActionItem "Turn on", MessageActionItem "Don't"]) - _ <- sendRequest SWindowShowMessageRequest params $ \case - Right (Just (MessageActionItem "Turn on")) -> do - let regOpts = CodeLensRegistrationOptions Nothing Nothing (Just False) + _ <- sendRequest SMethod_WindowShowMessageRequest params $ \case + Right (InL (MessageActionItem "Turn on")) -> do + let regOpts = CodeLensRegistrationOptions (InR Null) Nothing (Just False) - _ <- registerCapability STextDocumentCodeLens regOpts $ \_req responder -> do + _ <- registerCapability SMethod_TextDocumentCodeLens regOpts $ \_req responder -> do let cmd = Command "Say hello" "lsp-hello-command" Nothing - rsp = List [CodeLens (mkRange 0 0 0 100) (Just cmd) Nothing] - responder (Right rsp) + rsp = [CodeLens (mkRange 0 0 0 100) (Just cmd) Nothing] + responder $ Right $ InL rsp pure () Right _ -> - sendNotification SWindowShowMessage (ShowMessageParams MtInfo "Not turning on code lenses") + sendNotification SMethod_WindowShowMessage (ShowMessageParams MessageType_Info "Not turning on code lenses") Left err -> - sendNotification SWindowShowMessage (ShowMessageParams MtError $ "Something went wrong!\n" <> T.pack (show err)) + sendNotification SMethod_WindowShowMessage (ShowMessageParams MessageType_Error $ "Something went wrong!\n" <> T.pack (show err)) pure () - , requestHandler STextDocumentHover $ \req responder -> do - let RequestMessage _ _ _ (HoverParams _doc pos _workDone) = req + , requestHandler SMethod_TextDocumentHover $ \req responder -> do + let TRequestMessage _ _ _ (HoverParams _doc pos _workDone) = req Position _l _c' = pos - rsp = Hover ms (Just range) - ms = HoverContents $ markedUpContent "lsp-demo-simple-server" "Hello world" + rsp = Hover (InL ms) (Just range) + ms = markedUpContent "lsp-demo-simple-server" "Hello world" range = Range pos pos - responder (Right $ Just rsp) + responder (Right $ InL rsp) ] main :: IO Int diff --git a/lsp/lsp.cabal b/lsp/lsp.cabal index c06855edf..bf869e563 100644 --- a/lsp/lsp.cabal +++ b/lsp/lsp.cabal @@ -23,7 +23,6 @@ extra-source-files: ChangeLog.md, README.md library reexported-modules: Language.LSP.Types , Language.LSP.Types.Capabilities - , Language.LSP.Types.Lens exposed-modules: Language.LSP.Server , Language.LSP.Diagnostics , Language.LSP.Logging @@ -48,6 +47,7 @@ library , lens >= 4.15.2 , mtl < 2.4 , prettyprinter + , row-types , sorted-list == 0.2.1.* , stm == 2.5.* , temporary @@ -109,6 +109,7 @@ test-suite lsp-test , containers , lsp , hspec + , row-types , sorted-list == 0.2.1.* , text , text-rope diff --git a/lsp/src/Language/LSP/Diagnostics.hs b/lsp/src/Language/LSP/Diagnostics.hs index 5fc24ef02..7bb561350 100644 --- a/lsp/src/Language/LSP/Diagnostics.hs +++ b/lsp/src/Language/LSP/Diagnostics.hs @@ -23,6 +23,7 @@ module Language.LSP.Diagnostics import qualified Data.SortedList as SL import qualified Data.Map.Strict as Map import qualified Data.HashMap.Strict as HM +import Data.Text (Text) import qualified Language.LSP.Types as J -- --------------------------------------------------------------------- @@ -33,9 +34,9 @@ import qualified Language.LSP.Types as J {- We need a three level store - Uri : Maybe TextDocumentVersion : Maybe DiagnosticSource : [Diagnostics] + Uri : Maybe Int32 : Maybe DiagnosticSource : [Diagnostics] -For a given Uri, as soon as we see a new (Maybe TextDocumentVersion) we flush +For a given Uri, as soon as we see a new (Maybe Int32) we flush all prior entries for the Uri. -} @@ -43,10 +44,10 @@ all prior entries for the Uri. type DiagnosticStore = HM.HashMap J.NormalizedUri StoreItem data StoreItem - = StoreItem J.TextDocumentVersion DiagnosticsBySource + = StoreItem (Maybe J.Int32) DiagnosticsBySource deriving (Show,Eq) -type DiagnosticsBySource = Map.Map (Maybe J.DiagnosticSource) (SL.SortedList J.Diagnostic) +type DiagnosticsBySource = Map.Map (Maybe Text) (SL.SortedList J.Diagnostic) -- --------------------------------------------------------------------- @@ -55,7 +56,7 @@ partitionBySource diags = Map.fromListWith mappend $ map (\d -> (J._source d, (S -- --------------------------------------------------------------------- -flushBySource :: DiagnosticStore -> Maybe J.DiagnosticSource -> DiagnosticStore +flushBySource :: DiagnosticStore -> Maybe Text -> DiagnosticStore flushBySource store Nothing = store flushBySource store (Just source) = HM.map remove store where @@ -64,7 +65,7 @@ flushBySource store (Just source) = HM.map remove store -- --------------------------------------------------------------------- updateDiagnostics :: DiagnosticStore - -> J.NormalizedUri -> J.TextDocumentVersion -> DiagnosticsBySource + -> J.NormalizedUri -> Maybe J.Int32 -> DiagnosticsBySource -> DiagnosticStore updateDiagnostics store uri mv newDiagsBySource = r where @@ -92,6 +93,6 @@ getDiagnosticParamsFor maxDiagnostics ds uri = case HM.lookup uri ds of Nothing -> Nothing Just (StoreItem mv diags) -> - Just $ J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (fmap fromIntegral mv) (J.List (take maxDiagnostics $ SL.fromSortedList $ mconcat $ Map.elems diags)) + Just $ J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (fmap fromIntegral mv) (take maxDiagnostics $ SL.fromSortedList $ mconcat $ Map.elems diags) -- --------------------------------------------------------------------- diff --git a/lsp/src/Language/LSP/Logging.hs b/lsp/src/Language/LSP/Logging.hs index 2fb2d3dae..196c31b91 100644 --- a/lsp/src/Language/LSP/Logging.hs +++ b/lsp/src/Language/LSP/Logging.hs @@ -8,22 +8,22 @@ import Data.Text (Text) logSeverityToMessageType :: Severity -> MessageType logSeverityToMessageType sev = case sev of - Error -> MtError - Warning -> MtWarning - Info -> MtInfo - Debug -> MtLog + Error -> MessageType_Error + Warning -> MessageType_Warning + Info -> MessageType_Info + Debug -> MessageType_Log -- | Logs messages to the client via @window/logMessage@. logToLogMessage :: (MonadLsp c m) => LogAction m (WithSeverity Text) logToLogMessage = LogAction $ \(WithSeverity msg sev) -> do sendToClient $ fromServerNot $ - NotificationMessage "2.0" SWindowLogMessage (LogMessageParams (logSeverityToMessageType sev) msg) + TNotificationMessage "2.0" SMethod_WindowLogMessage (LogMessageParams (logSeverityToMessageType sev) msg) -- | Logs messages to the client via @window/showMessage@. logToShowMessage :: (MonadLsp c m) => LogAction m (WithSeverity Text) logToShowMessage = LogAction $ \(WithSeverity msg sev) -> do sendToClient $ fromServerNot $ - NotificationMessage "2.0" SWindowShowMessage (ShowMessageParams (logSeverityToMessageType sev) msg) + TNotificationMessage "2.0" SMethod_WindowShowMessage (ShowMessageParams (logSeverityToMessageType sev) msg) -- | A 'sensible' log action for logging messages to the client: -- diff --git a/lsp/src/Language/LSP/Server/Core.hs b/lsp/src/Language/LSP/Server/Core.hs index 82e19738b..6c135ee88 100644 --- a/lsp/src/Language/LSP/Server/Core.hs +++ b/lsp/src/Language/LSP/Server/Core.hs @@ -41,16 +41,17 @@ import qualified Data.List as L import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.Map.Strict as Map import Data.Maybe +import Data.Row import Data.Monoid (Ap(..)) import Data.Ord (Down (Down)) import qualified Data.Text as T import Data.Text ( Text ) import qualified Data.UUID as UUID import qualified Language.LSP.Types.Capabilities as J -import Language.LSP.Types as J +import Language.LSP.Types hiding (error) +import qualified Language.LSP.Types as J import Language.LSP.Types.SMethodMap (SMethodMap) import qualified Language.LSP.Types.SMethodMap as SMethodMap -import qualified Language.LSP.Types.Lens as J import Language.LSP.VFS import Language.LSP.Diagnostics import System.Random hiding (next) @@ -128,20 +129,20 @@ instance Semigroup (Handlers config) where instance Monoid (Handlers config) where mempty = Handlers mempty mempty -notificationHandler :: forall (m :: Method FromClient Notification) f. SMethod m -> Handler f m -> Handlers f +notificationHandler :: forall (m :: Method ClientToServer Notification) f. SMethod m -> Handler f m -> Handlers f notificationHandler m h = Handlers mempty (SMethodMap.singleton m (ClientMessageHandler h)) -requestHandler :: forall (m :: Method FromClient Request) f. SMethod m -> Handler f m -> Handlers f +requestHandler :: forall (m :: Method ClientToServer Request) f. SMethod m -> Handler f m -> Handlers f requestHandler m h = Handlers (SMethodMap.singleton m (ClientMessageHandler h)) mempty --- | Wrapper to restrict 'Handler's to 'FromClient' 'Method's -newtype ClientMessageHandler f (t :: MethodType) (m :: Method FromClient t) = ClientMessageHandler (Handler f m) +-- | Wrapper to restrict 'Handler's to ClientToServer' 'Method's +newtype ClientMessageHandler f (t :: MessageKind) (m :: Method ClientToServer t) = ClientMessageHandler (Handler f m) -- | The type of a handler that handles requests and notifications coming in -- from the server or client type family Handler (f :: Type -> Type) (m :: Method from t) = (result :: Type) | result -> f t m where - Handler f (m :: Method _from Request) = RequestMessage m -> (Either ResponseError (ResponseResult m) -> f ()) -> f () - Handler f (m :: Method _from Notification) = NotificationMessage m -> f () + Handler f (m :: Method _from Request) = TRequestMessage m -> (Either (TResponseError m) (MessageResult m) -> f ()) -> f () + Handler f (m :: Method _from Notification) = TNotificationMessage m -> f () -- | How to convert two isomorphic data structures between each other. data m <~> n @@ -154,8 +155,8 @@ transmuteHandlers :: (m <~> n) -> Handlers m -> Handlers n transmuteHandlers nat = mapHandlers (\i m k -> forward nat (i m (backward nat . k))) (\i m -> forward nat (i m)) mapHandlers - :: (forall (a :: Method FromClient Request). Handler m a -> Handler n a) - -> (forall (a :: Method FromClient Notification). Handler m a -> Handler n a) + :: (forall (a :: Method ClientToServer Request). Handler m a -> Handler n a) + -> (forall (a :: Method ClientToServer Notification). Handler m a -> Handler n a) -> Handlers m -> Handlers n mapHandlers mapReq mapNot (Handlers reqs nots) = Handlers reqs' nots' where @@ -178,10 +179,10 @@ data LanguageContextState config = type ResponseMap = IxMap LspId (Product SMethod ServerResponseCallback) -type RegistrationMap (t :: MethodType) = SMethodMap (Product RegistrationId (ClientMessageHandler IO t)) +type RegistrationMap (t :: MessageKind) = SMethodMap (Product RegistrationId (ClientMessageHandler IO t)) -data RegistrationToken (m :: Method FromClient t) = RegistrationToken (SMethod m) (RegistrationId m) -newtype RegistrationId (m :: Method FromClient t) = RegistrationId Text +data RegistrationToken (m :: Method ClientToServer t) = RegistrationToken (SMethod m) (RegistrationId m) +newtype RegistrationId (m :: Method ClientToServer t) = RegistrationId Text deriving Eq data ProgressData = ProgressData { progressNextId :: !(TVar Int32) @@ -217,32 +218,32 @@ getsState f = do -- If you set handlers for some requests, you may need to set some of these options. data Options = Options - { textDocumentSync :: Maybe J.TextDocumentSyncOptions + { optTextDocumentSync :: Maybe J.TextDocumentSyncOptions -- | The characters that trigger completion automatically. - , completionTriggerCharacters :: Maybe [Char] + , optCompletionTriggerCharacters :: Maybe [Char] -- | The list of all possible characters that commit a completion. This field can be used -- if clients don't support individual commit characters per completion item. See -- `_commitCharactersSupport`. - , completionAllCommitCharacters :: Maybe [Char] + , optCompletionAllCommitCharacters :: Maybe [Char] -- | The characters that trigger signature help automatically. - , signatureHelpTriggerCharacters :: Maybe [Char] + , optSignatureHelpTriggerCharacters :: Maybe [Char] -- | List of characters that re-trigger signature help. -- These trigger characters are only active when signature help is already showing. All trigger characters -- are also counted as re-trigger characters. - , signatureHelpRetriggerCharacters :: Maybe [Char] + , optSignatureHelpRetriggerCharacters :: Maybe [Char] -- | CodeActionKinds that this server may return. -- The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server -- may list out every specific kind they provide. - , codeActionKinds :: Maybe [CodeActionKind] + , optCodeActionKinds :: Maybe [CodeActionKind] -- | The list of characters that triggers on type formatting. -- If you set `documentOnTypeFormattingHandler`, you **must** set this. -- The first character is mandatory, so a 'NonEmpty' should be passed. - , documentOnTypeFormattingTriggerCharacters :: Maybe (NonEmpty Char) + , optDocumentOnTypeFormattingTriggerCharacters :: Maybe (NonEmpty Char) -- | The commands to be executed on the server. -- If you set `executeCommandHandler`, you **must** set this. - , executeCommandCommands :: Maybe [Text] + , optExecuteCommandCommands :: Maybe [Text] -- | Information about the server that can be advertised to the client. - , serverInfo :: Maybe J.ServerInfo + , optServerInfo :: Maybe (Rec ("name" .== Text .+ "version" .== Maybe Text)) } instance Default Options where @@ -285,7 +286,7 @@ data ServerDefinition config = forall m a. -- indicating what went wrong. The parsed configuration object will be -- stored internally and can be accessed via 'config'. -- It is also called on the `initializationOptions` field of the InitializeParams - , doInitialize :: LanguageContextEnv config -> Message Initialize -> IO (Either ResponseError a) + , doInitialize :: LanguageContextEnv config -> TMessage Method_Initialize -> IO (Either (TResponseError Method_Initialize) a) -- ^ Called *after* receiving the @initialize@ request and *before* -- returning the response. This callback will be invoked to offer the -- language server implementation the chance to create any processes or @@ -316,8 +317,8 @@ data ServerDefinition config = forall m a. -- | A function that a 'Handler' is passed that can be used to respond to a -- request with either an error, or the response params. -newtype ServerResponseCallback (m :: Method FromServer Request) - = ServerResponseCallback (Either ResponseError (ResponseResult m) -> IO ()) +newtype ServerResponseCallback (m :: Method ServerToClient Request) + = ServerResponseCallback (Either (TResponseError m) (MessageResult m) -> IO ()) -- | Return value signals if response handler was inserted successfully -- Might fail if the id was already in the map @@ -329,20 +330,20 @@ addResponseHandler lid h = do Nothing -> (False, pending) sendNotification - :: forall (m :: Method FromServer Notification) f config. MonadLsp config f + :: forall (m :: Method ServerToClient Notification) f config. MonadLsp config f => SServerMethod m -> MessageParams m -> f () sendNotification m params = - let msg = NotificationMessage "2.0" m params + let msg = TNotificationMessage "2.0" m params in case splitServerMethod m of IsServerNot -> sendToClient $ fromServerNot msg IsServerEither -> sendToClient $ FromServerMess m $ NotMess msg -sendRequest :: forall (m :: Method FromServer Request) f config. MonadLsp config f +sendRequest :: forall (m :: Method ServerToClient Request) f config. MonadLsp config f => SServerMethod m -> MessageParams m - -> (Either ResponseError (ResponseResult m) -> f ()) + -> (Either (TResponseError m) (MessageResult m) -> f ()) -> f (LspId m) sendRequest m params resHandler = do reqId <- IdInt <$> freshLspId @@ -350,7 +351,7 @@ sendRequest m params resHandler = do success <- addResponseHandler reqId (Pair m (ServerResponseCallback (rio . resHandler))) unless success $ error "LSP: could not send FromServer request as id is reused" - let msg = RequestMessage "2.0" reqId m params + let msg = TRequestMessage "2.0" reqId m params ~() <- case splitServerMethod m of IsServerReq -> sendToClient $ fromServerReq msg IsServerEither -> sendToClient $ FromServerMess m $ ReqMess msg @@ -403,8 +404,8 @@ getVersionedTextDoc doc = do let uri = doc ^. J.uri mvf <- getVirtualFile (toNormalizedUri uri) let ver = case mvf of - Just (VirtualFile lspver _ _) -> Just lspver - Nothing -> Nothing + Just (VirtualFile lspver _ _) -> lspver + Nothing -> 0 return (VersionedTextDocumentIdentifier uri ver) {-# INLINE getVersionedTextDoc #-} @@ -467,10 +468,7 @@ getRootPath = resRootPath <$> getLspEnv getWorkspaceFolders :: MonadLsp config m => m (Maybe [WorkspaceFolder]) getWorkspaceFolders = do clientCaps <- getClientCapabilities - let clientSupportsWfs = fromMaybe False $ do - let (J.ClientCapabilities mw _ _ _ _) = clientCaps - (J.WorkspaceClientCapabilities _ _ _ _ _ _ mwf _ _) <- mw - mwf + let clientSupportsWfs = fromMaybe False $ clientCaps ^? workspace . _Just . workspaceFolders . _Just if clientSupportsWfs then Just <$> getsState resWorkspaceFolders else pure Nothing @@ -481,7 +479,7 @@ getWorkspaceFolders = do -- a 'Method' with a 'Handler'. Returns 'Nothing' if the client does not -- support dynamic registration for the specified method, otherwise a -- 'RegistrationToken' which can be used to unregister it later. -registerCapability :: forall f t (m :: Method FromClient t) config. +registerCapability :: forall f t (m :: Method ClientToServer t) config. MonadLsp config f => SClientMethod m -> RegistrationOptions m @@ -503,8 +501,8 @@ registerCapability method regOpts f = do -- First, check to see if the client supports dynamic registration on this method | dynamicSupported clientCaps = do uuid <- liftIO $ UUID.toText <$> getStdRandom random - let registration = J.Registration uuid method (Just regOpts) - params = J.RegistrationParams (J.List [J.SomeRegistration registration]) + let registration = J.TRegistration uuid method (Just regOpts) + params = J.RegistrationParams [toUntypedRegistration registration] regId = RegistrationId uuid rio <- askUnliftIO ~() <- case splitClientMethod method of @@ -517,7 +515,7 @@ registerCapability method regOpts f = do IsClientEither -> error "Cannot register capability for custom methods" -- TODO: handle the scenario where this returns an error - _ <- sendRequest SClientRegisterCapability params $ \_res -> pure () + _ <- sendRequest SMethod_ClientRegisterCapability params $ \_res -> pure () pure (Just (RegistrationToken method regId)) | otherwise = pure Nothing @@ -530,37 +528,37 @@ registerCapability method regOpts f = do -- | Checks if client capabilities declares that the method supports dynamic registration dynamicSupported clientCaps = case method of - SWorkspaceDidChangeConfiguration -> capDyn $ clientCaps ^? J.workspace . _Just . J.didChangeConfiguration . _Just - SWorkspaceDidChangeWatchedFiles -> capDyn $ clientCaps ^? J.workspace . _Just . J.didChangeWatchedFiles . _Just - SWorkspaceSymbol -> capDyn $ clientCaps ^? J.workspace . _Just . J.symbol . _Just - SWorkspaceExecuteCommand -> capDyn $ clientCaps ^? J.workspace . _Just . J.executeCommand . _Just - STextDocumentDidOpen -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just - STextDocumentDidChange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just - STextDocumentDidClose -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just - STextDocumentCompletion -> capDyn $ clientCaps ^? J.textDocument . _Just . J.completion . _Just - STextDocumentHover -> capDyn $ clientCaps ^? J.textDocument . _Just . J.hover . _Just - STextDocumentSignatureHelp -> capDyn $ clientCaps ^? J.textDocument . _Just . J.signatureHelp . _Just - STextDocumentDeclaration -> capDyn $ clientCaps ^? J.textDocument . _Just . J.declaration . _Just - STextDocumentDefinition -> capDyn $ clientCaps ^? J.textDocument . _Just . J.definition . _Just - STextDocumentTypeDefinition -> capDyn $ clientCaps ^? J.textDocument . _Just . J.typeDefinition . _Just - STextDocumentImplementation -> capDyn $ clientCaps ^? J.textDocument . _Just . J.implementation . _Just - STextDocumentReferences -> capDyn $ clientCaps ^? J.textDocument . _Just . J.references . _Just - STextDocumentDocumentHighlight -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentHighlight . _Just - STextDocumentDocumentSymbol -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentSymbol . _Just - STextDocumentCodeAction -> capDyn $ clientCaps ^? J.textDocument . _Just . J.codeAction . _Just - STextDocumentCodeLens -> capDyn $ clientCaps ^? J.textDocument . _Just . J.codeLens . _Just - STextDocumentDocumentLink -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentLink . _Just - STextDocumentDocumentColor -> capDyn $ clientCaps ^? J.textDocument . _Just . J.colorProvider . _Just - STextDocumentColorPresentation -> capDyn $ clientCaps ^? J.textDocument . _Just . J.colorProvider . _Just - STextDocumentFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.formatting . _Just - STextDocumentRangeFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.rangeFormatting . _Just - STextDocumentOnTypeFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.onTypeFormatting . _Just - STextDocumentRename -> capDyn $ clientCaps ^? J.textDocument . _Just . J.rename . _Just - STextDocumentFoldingRange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.foldingRange . _Just - STextDocumentSelectionRange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.selectionRange . _Just - STextDocumentPrepareCallHierarchy -> capDyn $ clientCaps ^? J.textDocument . _Just . J.callHierarchy . _Just - STextDocumentSemanticTokens -> capDyn $ clientCaps ^? J.textDocument . _Just . J.semanticTokens . _Just - _ -> False + SMethod_WorkspaceDidChangeConfiguration -> capDyn $ clientCaps ^? J.workspace . _Just . J.didChangeConfiguration . _Just + SMethod_WorkspaceDidChangeWatchedFiles -> capDyn $ clientCaps ^? J.workspace . _Just . J.didChangeWatchedFiles . _Just + SMethod_WorkspaceSymbol -> capDyn $ clientCaps ^? J.workspace . _Just . J.symbol . _Just + SMethod_WorkspaceExecuteCommand -> capDyn $ clientCaps ^? J.workspace . _Just . J.executeCommand . _Just + SMethod_TextDocumentDidOpen -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just + SMethod_TextDocumentDidChange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just + SMethod_TextDocumentDidClose -> capDyn $ clientCaps ^? J.textDocument . _Just . J.synchronization . _Just + SMethod_TextDocumentCompletion -> capDyn $ clientCaps ^? J.textDocument . _Just . J.completion . _Just + SMethod_TextDocumentHover -> capDyn $ clientCaps ^? J.textDocument . _Just . J.hover . _Just + SMethod_TextDocumentSignatureHelp -> capDyn $ clientCaps ^? J.textDocument . _Just . J.signatureHelp . _Just + SMethod_TextDocumentDeclaration -> capDyn $ clientCaps ^? J.textDocument . _Just . J.declaration . _Just + SMethod_TextDocumentDefinition -> capDyn $ clientCaps ^? J.textDocument . _Just . J.definition . _Just + SMethod_TextDocumentTypeDefinition -> capDyn $ clientCaps ^? J.textDocument . _Just . J.typeDefinition . _Just + SMethod_TextDocumentImplementation -> capDyn $ clientCaps ^? J.textDocument . _Just . J.implementation . _Just + SMethod_TextDocumentReferences -> capDyn $ clientCaps ^? J.textDocument . _Just . J.references . _Just + SMethod_TextDocumentDocumentHighlight -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentHighlight . _Just + SMethod_TextDocumentDocumentSymbol -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentSymbol . _Just + SMethod_TextDocumentCodeAction -> capDyn $ clientCaps ^? J.textDocument . _Just . J.codeAction . _Just + SMethod_TextDocumentCodeLens -> capDyn $ clientCaps ^? J.textDocument . _Just . J.codeLens . _Just + SMethod_TextDocumentDocumentLink -> capDyn $ clientCaps ^? J.textDocument . _Just . J.documentLink . _Just + SMethod_TextDocumentDocumentColor -> capDyn $ clientCaps ^? J.textDocument . _Just . J.colorProvider . _Just + SMethod_TextDocumentColorPresentation -> capDyn $ clientCaps ^? J.textDocument . _Just . J.colorProvider . _Just + SMethod_TextDocumentFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.formatting . _Just + SMethod_TextDocumentRangeFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.rangeFormatting . _Just + SMethod_TextDocumentOnTypeFormatting -> capDyn $ clientCaps ^? J.textDocument . _Just . J.onTypeFormatting . _Just + SMethod_TextDocumentRename -> capDyn $ clientCaps ^? J.textDocument . _Just . J.rename . _Just + SMethod_TextDocumentFoldingRange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.foldingRange . _Just + SMethod_TextDocumentSelectionRange -> capDyn $ clientCaps ^? J.textDocument . _Just . J.selectionRange . _Just + SMethod_TextDocumentPrepareCallHierarchy -> capDyn $ clientCaps ^? J.textDocument . _Just . J.callHierarchy . _Just + --SMethod_TextDocumentSemanticTokens -> capDyn $ clientCaps ^? J.textDocument . _Just . J.semanticTokens . _Just + _ -> False -- | Sends a @client/unregisterCapability@ request and removes the handler -- for that associated registration. @@ -571,9 +569,9 @@ unregisterCapability (RegistrationToken m (RegistrationId uuid)) = do IsClientNot -> modifyState resRegistrationsNot $ SMethodMap.delete m IsClientEither -> error "Cannot unregister capability for custom methods" - let unregistration = J.Unregistration uuid (J.SomeClientMethod m) - params = J.UnregistrationParams (J.List [unregistration]) - void $ sendRequest SClientUnregisterCapability params $ \_res -> pure () + let unregistration = J.TUnregistration uuid m + params = J.UnregistrationParams [toUntypedUnregistration unregistration] + void $ sendRequest SMethod_ClientUnregisterCapability params $ \_res -> pure () -------------------------------------------------------------------------------- -- PROGRESS @@ -594,7 +592,7 @@ getNewProgressId :: MonadLsp config m => m ProgressToken getNewProgressId = do stateState (progressNextId . resProgressData) $ \cur -> let !next = cur+1 - in (ProgressNumericToken cur, next) + in (J.ProgressToken $ J.InL cur, next) {-# INLINE getNewProgressId #-} @@ -613,25 +611,25 @@ withProgressBase indefinite title cancellable f = do -- Create progress token -- FIXME : This needs to wait until the request returns before -- continuing!!! - _ <- sendRequest SWindowWorkDoneProgressCreate + _ <- sendRequest SMethod_WindowWorkDoneProgressCreate (WorkDoneProgressCreateParams progId) $ \res -> do case res of -- An error occurred when the client was setting it up -- No need to do anything then, as per the spec Left _err -> pure () - Right Empty -> pure () + Right _ -> pure () -- Send the begin and done notifications via 'bracket_' so that they are always fired res <- withRunInIO $ \runInBase -> E.bracket_ -- Send begin notification - (runInBase $ sendNotification SProgress $ - fmap Begin $ ProgressParams progId $ - WorkDoneProgressBeginParams title (Just cancellable') Nothing initialPercentage) + (runInBase $ sendNotification SMethod_Progress $ + ProgressParams progId $ J.toJSON $ + WorkDoneProgressBegin J.AString title (Just cancellable') Nothing initialPercentage) -- Send end notification - (runInBase $ sendNotification SProgress $ - End <$> ProgressParams progId (WorkDoneProgressEndParams Nothing)) $ do + (runInBase $ sendNotification SMethod_Progress $ + ProgressParams progId $ J.toJSON $ (WorkDoneProgressEnd J.AString Nothing)) $ do -- Run f asynchronously aid <- async $ runInBase $ f (updater progId) @@ -644,13 +642,11 @@ withProgressBase indefinite title cancellable f = do return res where updater progId (ProgressAmount percentage msg) = do - sendNotification SProgress $ fmap Report $ ProgressParams progId $ - WorkDoneProgressReportParams Nothing msg percentage + sendNotification SMethod_Progress $ ProgressParams progId $ J.toJSON $ + WorkDoneProgressReport J.AString Nothing msg percentage clientSupportsProgress :: J.ClientCapabilities -> Bool -clientSupportsProgress (J.ClientCapabilities _ _ wc _ _) = fromMaybe False $ do - (J.WindowClientCapabilities mProgress _ _) <- wc - mProgress +clientSupportsProgress caps = fromMaybe False $ caps ^? window . _Just . workDoneProgress . _Just {-# INLINE clientSupportsProgress #-} @@ -686,14 +682,14 @@ withIndefiniteProgress title cancellable f = do -- | Aggregate all diagnostics pertaining to a particular version of a document, -- by source, and sends a @textDocument/publishDiagnostics@ notification with -- the total (limited by the first parameter) whenever it is updated. -publishDiagnostics :: MonadLsp config m => Int -> NormalizedUri -> TextDocumentVersion -> DiagnosticsBySource -> m () +publishDiagnostics :: MonadLsp config m => Int -> NormalizedUri -> Maybe J.Int32 -> DiagnosticsBySource -> m () publishDiagnostics maxDiagnosticCount uri version diags = join $ stateState resDiagnostics $ \oldDiags-> let !newDiags = updateDiagnostics oldDiags uri version diags mdp = getDiagnosticParamsFor maxDiagnosticCount newDiags uri act = case mdp of Nothing -> return () Just params -> - sendToClient $ J.fromServerNot $ J.NotificationMessage "2.0" J.STextDocumentPublishDiagnostics params + sendToClient $ J.fromServerNot $ J.TNotificationMessage "2.0" J.SMethod_TextDocumentPublishDiagnostics params in (act,newDiags) -- --------------------------------------------------------------------- @@ -701,7 +697,7 @@ publishDiagnostics maxDiagnosticCount uri version diags = join $ stateState resD -- | Remove all diagnostics from a particular source, and send the updates to -- the client. flushDiagnosticsBySource :: MonadLsp config m => Int -- ^ Max number of diagnostics to send - -> Maybe DiagnosticSource -> m () + -> Maybe Text -> m () flushDiagnosticsBySource maxDiagnosticCount msource = join $ stateState resDiagnostics $ \oldDiags -> let !newDiags = flushBySource oldDiags msource -- Send the updated diagnostics to the client @@ -710,7 +706,7 @@ flushDiagnosticsBySource maxDiagnosticCount msource = join $ stateState resDiagn case mdp of Nothing -> return () Just params -> do - sendToClient $ J.fromServerNot $ J.NotificationMessage "2.0" J.STextDocumentPublishDiagnostics params + sendToClient $ J.fromServerNot $ J.TNotificationMessage "2.0" J.SMethod_TextDocumentPublishDiagnostics params in (act,newDiags) -- --------------------------------------------------------------------- @@ -720,17 +716,17 @@ flushDiagnosticsBySource maxDiagnosticCount msource = join $ stateState resDiagn reverseSortEdit :: J.WorkspaceEdit -> J.WorkspaceEdit reverseSortEdit (J.WorkspaceEdit cs dcs anns) = J.WorkspaceEdit cs' dcs' anns where - cs' :: Maybe J.WorkspaceEditMap + cs' :: Maybe (Map.Map Uri [TextEdit]) cs' = (fmap . fmap ) sortTextEdits cs - dcs' :: Maybe (J.List J.DocumentChange) + dcs' :: Maybe [J.DocumentChange] dcs' = (fmap . fmap) sortOnlyTextDocumentEdits dcs - sortTextEdits :: J.List J.TextEdit -> J.List J.TextEdit - sortTextEdits (J.List edits) = J.List (L.sortOn (Down . (^. J.range)) edits) + sortTextEdits :: [J.TextEdit] -> [J.TextEdit] + sortTextEdits edits = L.sortOn (Down . (^. J.range)) edits sortOnlyTextDocumentEdits :: J.DocumentChange -> J.DocumentChange - sortOnlyTextDocumentEdits (J.InL (J.TextDocumentEdit td (J.List edits))) = J.InL $ J.TextDocumentEdit td (J.List edits') + sortOnlyTextDocumentEdits (J.InL (J.TextDocumentEdit td edits)) = J.InL $ J.TextDocumentEdit td edits' where edits' = L.sortOn (Down . editRange) edits sortOnlyTextDocumentEdits (J.InR others) = J.InR others diff --git a/lsp/src/Language/LSP/Server/Processing.hs b/lsp/src/Language/LSP/Server/Processing.hs index 6488030b3..e21c71528 100644 --- a/lsp/src/Language/LSP/Server/Processing.hs +++ b/lsp/src/Language/LSP/Server/Processing.hs @@ -9,6 +9,7 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE StandaloneDeriving #-} +{-# LANGUAGE OverloadedLabels #-} {-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} -- So we can keep using the old prettyprinter modules (which have a better @@ -19,17 +20,18 @@ module Language.LSP.Server.Processing where import Colog.Core (LogAction (..), WithSeverity (..), Severity (..), (<&)) -import Control.Lens hiding (List, Empty) +import Control.Lens hiding (Empty) import Data.Aeson hiding (Options, Error) import Data.Aeson.Types hiding (Options, Error) import qualified Data.ByteString.Lazy as BSL import Data.List import Data.List.NonEmpty (NonEmpty(..)) +import Data.Row import qualified Data.Text as T import qualified Data.Text.Lazy.Encoding as TL -import Language.LSP.Types +import qualified Language.LSP.Types as LSP +import Language.LSP.Types hiding (error, id) import Language.LSP.Types.Capabilities -import qualified Language.LSP.Types.Lens as LSP import Language.LSP.Types.SMethodMap (SMethodMap) import qualified Language.LSP.Types.SMethodMap as SMethodMap import Language.LSP.Server.Core @@ -48,6 +50,7 @@ import Data.Maybe import qualified Data.Map.Strict as Map import Data.Text.Prettyprint.Doc import System.Exit +import GHC.TypeLits (symbolVal) import Data.Default (def) import Control.Monad.State import Control.Monad.Writer.Strict @@ -95,7 +98,7 @@ processMessage logger jsonStr = do pure $ handle logger m mess FromClientRsp (P.Pair (ServerResponseCallback f) (Const !newMap)) res -> do writeTVar pendingResponsesVar newMap - pure $ liftIO $ f (res ^. LSP.result) + pure $ liftIO $ f (res ^. result) where parser :: ResponseMap -> Value -> Parser (FromClientMessage' (P.Product ServerResponseCallback (Const ResponseMap))) parser rm = parseClientMessage $ \i -> @@ -109,25 +112,25 @@ initializeRequestHandler :: ServerDefinition config -> VFS -> (FromServerMessage -> IO ()) - -> Message Initialize + -> TMessage Method_Initialize -> IO (Maybe (LanguageContextEnv config)) initializeRequestHandler ServerDefinition{..} vfs sendFunc req = do - let sendResp = sendFunc . FromServerRsp SInitialize + let sendResp = sendFunc . FromServerRsp SMethod_Initialize handleErr (Left err) = do sendResp $ makeResponseError (req ^. LSP.id) err pure Nothing handleErr (Right a) = pure $ Just a flip E.catch (initializeErrorHandler $ sendResp . makeResponseError (req ^. LSP.id)) $ handleErr <=< runExceptT $ mdo - let params = req ^. LSP.params - rootDir = getFirst $ foldMap First [ params ^. LSP.rootUri >>= uriToFilePath - , params ^. LSP.rootPath <&> T.unpack ] + let p = req ^. params + rootDir = getFirst $ foldMap First [ p ^? rootUri . _L >>= uriToFilePath + , p ^? rootPath . _Just . _L <&> T.unpack ] - let initialWfs = case params ^. LSP.workspaceFolders of - Just (List xs) -> xs - Nothing -> [] + let initialWfs = case p ^. workspaceFolders of + Just (InL xs) -> xs + _ -> [] - initialConfig = case onConfigurationChange defaultConfig <$> (req ^. LSP.params . LSP.initializationOptions) of + initialConfig = case onConfigurationChange defaultConfig <$> (p ^. initializationOptions) of Just (Right newConfig) -> newConfig _ -> defaultConfig @@ -147,21 +150,21 @@ initializeRequestHandler ServerDefinition{..} vfs sendFunc req = do pure LanguageContextState{..} -- Call the 'duringInitialization' callback to let the server kick stuff up - let env = LanguageContextEnv handlers onConfigurationChange sendFunc stateVars (params ^. LSP.capabilities) rootDir + let env = LanguageContextEnv handlers onConfigurationChange sendFunc stateVars (p ^. capabilities) rootDir handlers = transmuteHandlers interpreter staticHandlers interpreter = interpretHandler initializationResult initializationResult <- ExceptT $ doInitialize env req - let serverCaps = inferServerCapabilities (params ^. LSP.capabilities) options handlers - liftIO $ sendResp $ makeResponseMessage (req ^. LSP.id) (InitializeResult serverCaps (serverInfo options)) + let serverCaps = inferServerCapabilities (p ^. capabilities) options handlers + liftIO $ sendResp $ makeResponseMessage (req ^. LSP.id) (InitializeResult serverCaps (optServerInfo options)) pure env where - makeResponseMessage rid result = ResponseMessage "2.0" (Just rid) (Right result) - makeResponseError origId err = ResponseMessage "2.0" (Just origId) (Left err) + makeResponseMessage rid result = TResponseMessage "2.0" (Just rid) (Right result) + makeResponseError origId err = TResponseMessage "2.0" (Just origId) (Left err) - initializeErrorHandler :: (ResponseError -> IO ()) -> E.SomeException -> IO (Maybe a) + initializeErrorHandler :: (TResponseError Method_Initialize -> IO ()) -> E.SomeException -> IO (Maybe a) initializeErrorHandler sendResp e = do - sendResp $ ResponseError InternalError msg Nothing + sendResp $ TResponseError ErrorCodes_InternalError msg Nothing pure Nothing where msg = T.pack $ unwords ["Error on initialize:", show e] @@ -174,37 +177,46 @@ inferServerCapabilities :: ClientCapabilities -> Options -> Handlers m -> Server inferServerCapabilities clientCaps o h = ServerCapabilities { _textDocumentSync = sync - , _hoverProvider = supportedBool STextDocumentHover + , _hoverProvider = supportedBool SMethod_TextDocumentHover , _completionProvider = completionProvider - , _declarationProvider = supportedBool STextDocumentDeclaration + , _declarationProvider = supportedBool SMethod_TextDocumentDeclaration , _signatureHelpProvider = signatureHelpProvider - , _definitionProvider = supportedBool STextDocumentDefinition - , _typeDefinitionProvider = supportedBool STextDocumentTypeDefinition - , _implementationProvider = supportedBool STextDocumentImplementation - , _referencesProvider = supportedBool STextDocumentReferences - , _documentHighlightProvider = supportedBool STextDocumentDocumentHighlight - , _documentSymbolProvider = supportedBool STextDocumentDocumentSymbol + , _definitionProvider = supportedBool SMethod_TextDocumentDefinition + , _typeDefinitionProvider = supportedBool SMethod_TextDocumentTypeDefinition + , _implementationProvider = supportedBool SMethod_TextDocumentImplementation + , _referencesProvider = supportedBool SMethod_TextDocumentReferences + , _documentHighlightProvider = supportedBool SMethod_TextDocumentDocumentHighlight + , _documentSymbolProvider = supportedBool SMethod_TextDocumentDocumentSymbol , _codeActionProvider = codeActionProvider - , _codeLensProvider = supported' STextDocumentCodeLens $ CodeLensOptions + , _codeLensProvider = supported' SMethod_TextDocumentCodeLens $ CodeLensOptions (Just False) - (supported SCodeLensResolve) - , _documentFormattingProvider = supportedBool STextDocumentFormatting - , _documentRangeFormattingProvider = supportedBool STextDocumentRangeFormatting + (supported SMethod_CodeLensResolve) + , _documentFormattingProvider = supportedBool SMethod_TextDocumentFormatting + , _documentRangeFormattingProvider = supportedBool SMethod_TextDocumentRangeFormatting , _documentOnTypeFormattingProvider = documentOnTypeFormattingProvider , _renameProvider = renameProvider - , _documentLinkProvider = supported' STextDocumentDocumentLink $ DocumentLinkOptions + , _documentLinkProvider = supported' SMethod_TextDocumentDocumentLink $ DocumentLinkOptions (Just False) - (supported SDocumentLinkResolve) - , _colorProvider = supportedBool STextDocumentDocumentColor - , _foldingRangeProvider = supportedBool STextDocumentFoldingRange + (supported SMethod_DocumentLinkResolve) + , _colorProvider = supportedBool SMethod_TextDocumentDocumentColor + , _foldingRangeProvider = supportedBool SMethod_TextDocumentFoldingRange , _executeCommandProvider = executeCommandProvider - , _selectionRangeProvider = supportedBool STextDocumentSelectionRange - , _callHierarchyProvider = supportedBool STextDocumentPrepareCallHierarchy + , _selectionRangeProvider = supportedBool SMethod_TextDocumentSelectionRange + , _callHierarchyProvider = supportedBool SMethod_TextDocumentPrepareCallHierarchy , _semanticTokensProvider = semanticTokensProvider - , _workspaceSymbolProvider = supportedBool SWorkspaceSymbol + , _workspaceSymbolProvider = supportedBool SMethod_WorkspaceSymbol , _workspace = Just workspace -- TODO: Add something for experimental , _experimental = Nothing :: Maybe Value + -- TODO + , _positionEncoding = Nothing + , _notebookDocumentSync = Nothing + , _linkedEditingRangeProvider = Nothing + , _monikerProvider = Nothing + , _typeHierarchyProvider = Nothing + , _inlineValueProvider = Nothing + , _inlayHintProvider = Nothing + , _diagnosticProvider = Nothing } where @@ -229,102 +241,104 @@ inferServerCapabilities clientCaps o h = singleton x = [x] completionProvider - | supported_b STextDocumentCompletion = Just $ - CompletionOptions - Nothing - (map T.singleton <$> completionTriggerCharacters o) - (map T.singleton <$> completionAllCommitCharacters o) - (supported SCompletionItemResolve) + | supported_b SMethod_TextDocumentCompletion = Just $ + CompletionOptions { + _triggerCharacters=map T.singleton <$> optCompletionTriggerCharacters o + , _allCommitCharacters=map T.singleton <$> optCompletionAllCommitCharacters o + , _resolveProvider=supported SMethod_CompletionItemResolve + , _completionItem=Nothing + , _workDoneProgress=Nothing + } | otherwise = Nothing clientSupportsCodeActionKinds = isJust $ - clientCaps ^? LSP.textDocument . _Just . LSP.codeAction . _Just . LSP.codeActionLiteralSupport + clientCaps ^? textDocument . _Just . codeAction . _Just . codeActionLiteralSupport codeActionProvider | clientSupportsCodeActionKinds - , supported_b STextDocumentCodeAction = Just $ case codeActionKinds o of - Just ks -> InR $ CodeActionOptions Nothing (Just (List ks)) (supported SCodeLensResolve) + , supported_b SMethod_TextDocumentCodeAction = Just $ case optCodeActionKinds o of + Just ks -> InR $ CodeActionOptions Nothing (Just ks) (supported SMethod_CodeLensResolve) Nothing -> InL True - | supported_b STextDocumentCodeAction = Just (InL True) + | supported_b SMethod_TextDocumentCodeAction = Just (InL True) | otherwise = Just (InL False) signatureHelpProvider - | supported_b STextDocumentSignatureHelp = Just $ + | supported_b SMethod_TextDocumentSignatureHelp = Just $ SignatureHelpOptions Nothing - (List . map T.singleton <$> signatureHelpTriggerCharacters o) - (List . map T.singleton <$> signatureHelpRetriggerCharacters o) + (map T.singleton <$> optSignatureHelpTriggerCharacters o) + (map T.singleton <$> optSignatureHelpRetriggerCharacters o) | otherwise = Nothing documentOnTypeFormattingProvider - | supported_b STextDocumentOnTypeFormatting - , Just (first :| rest) <- documentOnTypeFormattingTriggerCharacters o = Just $ + | supported_b SMethod_TextDocumentOnTypeFormatting + , Just (first :| rest) <- optDocumentOnTypeFormattingTriggerCharacters o = Just $ DocumentOnTypeFormattingOptions (T.pack [first]) (Just (map (T.pack . singleton) rest)) - | supported_b STextDocumentOnTypeFormatting - , Nothing <- documentOnTypeFormattingTriggerCharacters o = + | supported_b SMethod_TextDocumentOnTypeFormatting + , Nothing <- optDocumentOnTypeFormattingTriggerCharacters o = error "documentOnTypeFormattingTriggerCharacters needs to be set if a documentOnTypeFormattingHandler is set" | otherwise = Nothing executeCommandProvider - | supported_b SWorkspaceExecuteCommand - , Just cmds <- executeCommandCommands o = Just (ExecuteCommandOptions Nothing (List cmds)) - | supported_b SWorkspaceExecuteCommand - , Nothing <- executeCommandCommands o = + | supported_b SMethod_WorkspaceExecuteCommand + , Just cmds <- optExecuteCommandCommands o = Just (ExecuteCommandOptions Nothing cmds) + | supported_b SMethod_WorkspaceExecuteCommand + , Nothing <- optExecuteCommandCommands o = error "executeCommandCommands needs to be set if a executeCommandHandler is set" | otherwise = Nothing clientSupportsPrepareRename = fromMaybe False $ - clientCaps ^? LSP.textDocument . _Just . LSP.rename . _Just . LSP.prepareSupport . _Just + clientCaps ^? textDocument . _Just . rename . _Just . prepareSupport . _Just renameProvider | clientSupportsPrepareRename - , supported_b STextDocumentRename - , supported_b STextDocumentPrepareRename = Just $ + , supported_b SMethod_TextDocumentRename + , supported_b SMethod_TextDocumentPrepareRename = Just $ InR . RenameOptions Nothing . Just $ True - | supported_b STextDocumentRename = Just (InL True) + | supported_b SMethod_TextDocumentRename = Just (InL True) | otherwise = Just (InL False) -- Always provide the default legend -- TODO: allow user-provided legend via 'Options', or at least user-provided types - semanticTokensProvider = Just $ InL $ SemanticTokensOptions Nothing def semanticTokenRangeProvider semanticTokenFullProvider + semanticTokensProvider = Just $ InL $ SemanticTokensOptions Nothing defaultSemanticTokensLegend semanticTokenRangeProvider semanticTokenFullProvider semanticTokenRangeProvider - | supported_b STextDocumentSemanticTokensRange = Just $ SemanticTokensRangeBool True + | supported_b SMethod_TextDocumentSemanticTokensRange = Just $ InL True | otherwise = Nothing semanticTokenFullProvider - | supported_b STextDocumentSemanticTokensFull = Just $ SemanticTokensFullDelta $ SemanticTokensDeltaClientCapabilities $ supported STextDocumentSemanticTokensFullDelta + | supported_b SMethod_TextDocumentSemanticTokensFull = Just $ InR $ #delta .== supported SMethod_TextDocumentSemanticTokensFullDelta | otherwise = Nothing - sync = case textDocumentSync o of + sync = case optTextDocumentSync o of Just x -> Just (InL x) Nothing -> Nothing - workspace = WorkspaceServerCapabilities workspaceFolder - workspaceFolder = supported' SWorkspaceDidChangeWorkspaceFolders $ + workspace = #workspaceFolders .== workspaceFolder .+ #fileOperations .== Nothing + workspaceFolder = supported' SMethod_WorkspaceDidChangeWorkspaceFolders $ -- sign up to receive notifications WorkspaceFoldersServerCapabilities (Just True) (Just (InR True)) -- | Invokes the registered dynamic or static handlers for the given message and -- method, as well as doing some bookkeeping. -handle :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> SClientMethod meth -> ClientMessage meth -> m () +handle :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> SClientMethod meth -> TClientMessage meth -> m () handle logger m msg = case m of - SWorkspaceDidChangeWorkspaceFolders -> handle' logger (Just updateWorkspaceFolders) m msg - SWorkspaceDidChangeConfiguration -> handle' logger (Just $ handleConfigChange logger) m msg - STextDocumentDidOpen -> handle' logger (Just $ vfsFunc logger openVFS) m msg - STextDocumentDidChange -> handle' logger (Just $ vfsFunc logger changeFromClientVFS) m msg - STextDocumentDidClose -> handle' logger (Just $ vfsFunc logger closeVFS) m msg - SWindowWorkDoneProgressCancel -> handle' logger (Just $ progressCancelHandler logger) m msg + SMethod_WorkspaceDidChangeWorkspaceFolders -> handle' logger (Just updateWorkspaceFolders) m msg + SMethod_WorkspaceDidChangeConfiguration -> handle' logger (Just $ handleConfigChange logger) m msg + SMethod_TextDocumentDidOpen -> handle' logger (Just $ vfsFunc logger openVFS) m msg + SMethod_TextDocumentDidChange -> handle' logger (Just $ vfsFunc logger changeFromClientVFS) m msg + SMethod_TextDocumentDidClose -> handle' logger (Just $ vfsFunc logger closeVFS) m msg + SMethod_WindowWorkDoneProgressCancel -> handle' logger (Just $ progressCancelHandler logger) m msg _ -> handle' logger Nothing m msg -handle' :: forall m t (meth :: Method FromClient t) config +handle' :: forall m t (meth :: Method ClientToServer t) config . (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) - -> Maybe (ClientMessage meth -> m ()) + -> Maybe (TClientMessage meth -> m ()) -- ^ An action to be run before invoking the handler, used for -- bookkeeping stuff like the vfs etc. -> SClientMethod meth - -> ClientMessage meth + -> TClientMessage meth -> m () handle' logger mAction m msg = do maybe (return ()) (\f -> f msg) mAction @@ -335,29 +349,29 @@ handle' logger mAction m msg = do env <- getLspEnv let Handlers{reqHandlers, notHandlers} = resHandlers env - let mkRspCb :: RequestMessage (m1 :: Method FromClient Request) -> Either ResponseError (ResponseResult m1) -> IO () + let mkRspCb :: TRequestMessage (m1 :: Method ClientToServer Request) -> Either (TResponseError m1) (MessageResult m1) -> IO () mkRspCb req (Left err) = runLspT env $ sendToClient $ - FromServerRsp (req ^. LSP.method) $ ResponseMessage "2.0" (Just (req ^. LSP.id)) (Left err) + FromServerRsp (req ^. method) $ TResponseMessage "2.0" (Just (req ^. LSP.id)) (Left err) mkRspCb req (Right rsp) = runLspT env $ sendToClient $ - FromServerRsp (req ^. LSP.method) $ ResponseMessage "2.0" (Just (req ^. LSP.id)) (Right rsp) + FromServerRsp (req ^. method) $ TResponseMessage "2.0" (Just (req ^. LSP.id)) (Right rsp) case splitClientMethod m of IsClientNot -> case pickHandler dynNotHandlers notHandlers of Just h -> liftIO $ h msg Nothing - | SExit <- m -> exitNotificationHandler logger msg + | SMethod_Exit <- m -> exitNotificationHandler logger msg | otherwise -> do reportMissingHandler IsClientReq -> case pickHandler dynReqHandlers reqHandlers of Just h -> liftIO $ h msg (mkRspCb msg) Nothing - | SShutdown <- m -> liftIO $ shutdownRequestHandler msg (mkRspCb msg) + | SMethod_Shutdown <- m -> liftIO $ shutdownRequestHandler msg (mkRspCb msg) | otherwise -> do let errorMsg = T.pack $ unwords ["lsp:no handler for: ", show m] - err = ResponseError MethodNotFound errorMsg Nothing + err = TResponseError ErrorCodes_MethodNotFound errorMsg Nothing sendToClient $ - FromServerRsp (msg ^. LSP.method) $ ResponseMessage "2.0" (Just (msg ^. LSP.id)) (Left err) + FromServerRsp (msg ^. method) $ TResponseMessage "2.0" (Just (msg ^. LSP.id)) (Left err) IsClientEither -> case msg of NotMess noti -> case pickHandler dynNotHandlers notHandlers of @@ -367,9 +381,9 @@ handle' logger mAction m msg = do Just h -> liftIO $ h req (mkRspCb req) Nothing -> do let errorMsg = T.pack $ unwords ["lsp:no handler for: ", show m] - err = ResponseError MethodNotFound errorMsg Nothing + err = TResponseError ErrorCodes_MethodNotFound errorMsg Nothing sendToClient $ - FromServerRsp (req ^. LSP.method) $ ResponseMessage "2.0" (Just (req ^. LSP.id)) (Left err) + FromServerRsp (req ^. method) $ TResponseMessage "2.0" (Just (req ^. LSP.id)) (Left err) where -- | Checks to see if there's a dynamic handler, and uses it in favour of the -- static handler, if it exists. @@ -386,12 +400,12 @@ handle' logger mAction m msg = do reportMissingHandler = let optional = isOptionalNotification m in logger <& MissingHandler optional m `WithSeverity` if optional then Warning else Error - isOptionalNotification (SCustomMethod method) - | "$/" `T.isPrefixOf` method = True + isOptionalNotification (SMethod_CustomMethod p) + | "$/" `T.isPrefixOf` T.pack (symbolVal p) = True isOptionalNotification _ = False -progressCancelHandler :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> Message WindowWorkDoneProgressCancel -> m () -progressCancelHandler logger (NotificationMessage _ _ (WorkDoneProgressCancelParams tid)) = do +progressCancelHandler :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> TMessage Method_WindowWorkDoneProgressCancel -> m () +progressCancelHandler logger (TNotificationMessage _ _ (WorkDoneProgressCancelParams tid)) = do pdata <- getsState (progressCancel . resProgressData) case Map.lookup tid pdata of Nothing -> return () @@ -399,26 +413,26 @@ progressCancelHandler logger (NotificationMessage _ _ (WorkDoneProgressCancelPar logger <& ProgressCancel tid `WithSeverity` Debug liftIO cancelAction -exitNotificationHandler :: (MonadIO m) => LogAction m (WithSeverity LspProcessingLog) -> Handler m Exit +exitNotificationHandler :: (MonadIO m) => LogAction m (WithSeverity LspProcessingLog) -> Handler m Method_Exit exitNotificationHandler logger _ = do logger <& Exiting `WithSeverity` Info liftIO exitSuccess -- | Default Shutdown handler -shutdownRequestHandler :: Handler IO Shutdown +shutdownRequestHandler :: Handler IO Method_Shutdown shutdownRequestHandler _req k = do - k $ Right Empty + k $ Right LSP.Null -handleConfigChange :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> Message WorkspaceDidChangeConfiguration -> m () +handleConfigChange :: (m ~ LspM config) => LogAction m (WithSeverity LspProcessingLog) -> TMessage Method_WorkspaceDidChangeConfiguration -> m () handleConfigChange logger req = do parseConfig <- LspT $ asks resParseConfig - let settings = req ^. LSP.params . LSP.settings - res <- stateState resConfig $ \oldConfig -> case parseConfig oldConfig settings of + let s = req ^. params . settings + res <- stateState resConfig $ \oldConfig -> case parseConfig oldConfig s of Left err -> (Left err, oldConfig) Right !newConfig -> (Right (), newConfig) case res of Left err -> do - logger <& ConfigurationParseError settings err `WithSeverity` Error + logger <& ConfigurationParseError s err `WithSeverity` Error Right () -> pure () vfsFunc :: forall m n a config @@ -443,10 +457,10 @@ vfsFunc logger modifyVfs req = do innerLogger = LogAction $ \m -> tell [m] -- | Updates the list of workspace folders -updateWorkspaceFolders :: Message WorkspaceDidChangeWorkspaceFolders -> LspM config () -updateWorkspaceFolders (NotificationMessage _ _ params) = do - let List toRemove = params ^. LSP.event . LSP.removed - List toAdd = params ^. LSP.event . LSP.added +updateWorkspaceFolders :: TMessage Method_WorkspaceDidChangeWorkspaceFolders -> LspM config () +updateWorkspaceFolders (TNotificationMessage _ _ params) = do + let toRemove = params ^. event . removed + toAdd = params ^. event . added newWfs oldWfs = foldr delete oldWfs toRemove <> toAdd modifyState resWorkspaceFolders newWfs diff --git a/lsp/src/Language/LSP/VFS.hs b/lsp/src/Language/LSP/VFS.hs index 17915da0d..4938370b0 100644 --- a/lsp/src/Language/LSP/VFS.hs +++ b/lsp/src/Language/LSP/VFS.hs @@ -1,6 +1,7 @@ {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} @@ -77,8 +78,8 @@ import qualified Data.Text as T import qualified Data.Text.IO as T import Data.Int (Int32) import Data.List +import Data.Row import Data.Ord -import qualified Data.HashMap.Strict as HashMap import qualified Data.Map.Strict as Map import Data.Maybe import qualified Data.Text.Rope as URope @@ -86,7 +87,6 @@ import Data.Text.Utf16.Rope ( Rope ) import qualified Data.Text.Utf16.Rope as Rope import Data.Text.Prettyprint.Doc hiding (line) import qualified Language.LSP.Types as J -import qualified Language.LSP.Types.Lens as J import System.FilePath import Data.Hashable import System.Directory @@ -151,7 +151,7 @@ initVFS k = withSystemTempDirectory "haskell-lsp" $ \temp_dir -> k (VFS mempty t -- --------------------------------------------------------------------- -- | Applies the changes from a 'J.DidOpenTextDocument' to the 'VFS' -openVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.Message 'J.TextDocumentDidOpen -> m () +openVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.TMessage 'J.Method_TextDocumentDidOpen -> m () openVFS logger msg = do let J.TextDocumentItem (J.toNormalizedUri -> uri) _ version text = msg ^. J.params . J.textDocument vfile = VirtualFile version 0 (Rope.fromText text) @@ -161,12 +161,12 @@ openVFS logger msg = do -- --------------------------------------------------------------------- -- | Applies a 'DidChangeTextDocumentNotification' to the 'VFS' -changeFromClientVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.Message 'J.TextDocumentDidChange -> m () +changeFromClientVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.TMessage 'J.Method_TextDocumentDidChange -> m () changeFromClientVFS logger msg = do let - J.DidChangeTextDocumentParams vid (J.List changes) = msg ^. J.params + J.DidChangeTextDocumentParams vid changes = msg ^. J.params -- the client shouldn't be sending over a null version, only the server, but we just use 0 if that happens - J.VersionedTextDocumentIdentifier (J.toNormalizedUri -> uri) (fromMaybe 0 -> version) = vid + J.VersionedTextDocumentIdentifier (J.toNormalizedUri -> uri) version = vid vfs <- get case vfs ^. vfsMap . at uri of Just (VirtualFile _ file_ver contents) -> do @@ -177,7 +177,7 @@ changeFromClientVFS logger msg = do -- --------------------------------------------------------------------- applyCreateFile :: (MonadState VFS m) => J.CreateFile -> m () -applyCreateFile (J.CreateFile (J.toNormalizedUri -> uri) options _ann) = +applyCreateFile (J.CreateFile _ann _kind (J.toNormalizedUri -> uri) options) = vfsMap %= Map.insertWith (\ new old -> if shouldOverwrite then new else old) uri @@ -197,7 +197,7 @@ applyCreateFile (J.CreateFile (J.toNormalizedUri -> uri) options _ann) = Just (J.CreateFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists` applyRenameFile :: (MonadState VFS m) => J.RenameFile -> m () -applyRenameFile (J.RenameFile (J.toNormalizedUri -> oldUri) (J.toNormalizedUri -> newUri) options _ann) = do +applyRenameFile (J.RenameFile _ann _kind (J.toNormalizedUri -> oldUri) (J.toNormalizedUri -> newUri) options) = do vfs <- get case vfs ^. vfsMap . at oldUri of -- nothing to rename @@ -225,7 +225,7 @@ applyRenameFile (J.RenameFile (J.toNormalizedUri -> oldUri) (J.toNormalizedUri - Just (J.RenameFileOptions (Just False) (Just False)) -> False -- `overwrite` wins over `ignoreIfExists` applyDeleteFile :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.DeleteFile -> m () -applyDeleteFile logger (J.DeleteFile (J.toNormalizedUri -> uri) options _ann) = do +applyDeleteFile logger (J.DeleteFile _ann _kind (J.toNormalizedUri -> uri) options) = do -- NOTE: we are ignoring the `recursive` option here because we don't know which file is a directory when (options ^? _Just . J.recursive . _Just == Just True) $ logger <& CantRecursiveDelete uri `WithSeverity` Warning @@ -239,13 +239,15 @@ applyDeleteFile logger (J.DeleteFile (J.toNormalizedUri -> uri) options _ann) = _ -> pure () applyTextDocumentEdit :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.TextDocumentEdit -> m () -applyTextDocumentEdit logger (J.TextDocumentEdit vid (J.List edits)) = do +applyTextDocumentEdit logger (J.TextDocumentEdit vid edits) = do -- all edits are supposed to be applied at once -- so apply from bottom up so they don't affect others let sortedEdits = sortOn (Down . editRange) edits changeEvents = map editToChangeEvent sortedEdits - ps = J.DidChangeTextDocumentParams vid (J.List changeEvents) - notif = J.NotificationMessage "" J.STextDocumentDidChange ps + -- TODO: is this right? + vid' = J.VersionedTextDocumentIdentifier (vid ^. J.uri) (case vid ^. J.version of {J.InL v -> v; J.InR _ -> 0}) + ps = J.DidChangeTextDocumentParams vid' changeEvents + notif = J.TNotificationMessage "" J.SMethod_TextDocumentDidChange ps changeFromClientVFS logger notif where @@ -254,8 +256,8 @@ applyTextDocumentEdit logger (J.TextDocumentEdit vid (J.List edits)) = do editRange (J.InL e) = e ^. J.range editToChangeEvent :: J.TextEdit J.|? J.AnnotatedTextEdit -> J.TextDocumentContentChangeEvent - editToChangeEvent (J.InR e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText) - editToChangeEvent (J.InL e) = J.TextDocumentContentChangeEvent (Just $ e ^. J.range) Nothing (e ^. J.newText) + editToChangeEvent (J.InR e) = J.TextDocumentContentChangeEvent $ J.InL $ #range .== e ^. J.range .+ #rangeLength .== Nothing .+ #text .== e ^. J.newText + editToChangeEvent (J.InL e) = J.TextDocumentContentChangeEvent $ J.InL $ #range .== e ^. J.range .+ #rangeLength .== Nothing .+ #text .== e ^. J.newText applyDocumentChange :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.DocumentChange -> m () applyDocumentChange logger (J.InL change) = applyTextDocumentEdit logger change @@ -264,26 +266,28 @@ applyDocumentChange _ (J.InR (J.InR (J.InL change))) = applyRenameFile chan applyDocumentChange logger (J.InR (J.InR (J.InR change))) = applyDeleteFile logger change -- | Applies the changes from a 'ApplyWorkspaceEditRequest' to the 'VFS' -changeFromServerVFS :: forall m . MonadState VFS m => LogAction m (WithSeverity VfsLog) -> J.Message 'J.WorkspaceApplyEdit -> m () +changeFromServerVFS :: forall m . MonadState VFS m => LogAction m (WithSeverity VfsLog) -> J.TMessage 'J.Method_WorkspaceApplyEdit -> m () changeFromServerVFS logger msg = do let J.ApplyWorkspaceEditParams _label edit = msg ^. J.params J.WorkspaceEdit mChanges mDocChanges _anns = edit case mDocChanges of - Just (J.List docChanges) -> applyDocumentChanges docChanges + Just docChanges -> applyDocumentChanges docChanges Nothing -> case mChanges of - Just cs -> applyDocumentChanges $ map J.InL $ HashMap.foldlWithKey' changeToTextDocumentEdit [] cs + Just cs -> applyDocumentChanges $ map J.InL $ Map.foldlWithKey' changeToTextDocumentEdit [] cs Nothing -> pure () where changeToTextDocumentEdit acc uri edits = - acc ++ [J.TextDocumentEdit (J.VersionedTextDocumentIdentifier uri (Just 0)) (fmap J.InL edits)] + acc ++ [J.TextDocumentEdit (J.OptionalVersionedTextDocumentIdentifier uri (J.InL 0)) (fmap J.InL edits)] applyDocumentChanges :: [J.DocumentChange] -> m () applyDocumentChanges = traverse_ (applyDocumentChange logger) . sortOn project -- for sorting [DocumentChange] - project :: J.DocumentChange -> J.TextDocumentVersion -- type TextDocumentVersion = Maybe Int - project (J.InL textDocumentEdit) = textDocumentEdit ^. J.textDocument . J.version + project :: J.DocumentChange -> Maybe J.Int32 + project (J.InL textDocumentEdit) = case textDocumentEdit ^. J.textDocument . J.version of + J.InL v -> Just v + _ -> Nothing project _ = Nothing -- --------------------------------------------------------------------- @@ -322,7 +326,7 @@ persistFileVFS logger vfs uri = -- --------------------------------------------------------------------- -closeVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.Message 'J.TextDocumentDidClose -> m () +closeVFS :: (MonadState VFS m) => LogAction m (WithSeverity VfsLog) -> J.TMessage 'J.Method_TextDocumentDidClose -> m () closeVFS logger msg = do let J.DidCloseTextDocumentParams (J.TextDocumentIdentifier (J.toNormalizedUri -> uri)) = msg ^. J.params logger <& Closing uri `WithSeverity` Debug @@ -339,10 +343,10 @@ applyChanges logger = foldM (applyChange logger) -- --------------------------------------------------------------------- applyChange :: (Monad m) => LogAction m (WithSeverity VfsLog) -> Rope -> J.TextDocumentContentChangeEvent -> m Rope -applyChange _ _ (J.TextDocumentContentChangeEvent Nothing _ str) - = pure $ Rope.fromText str -applyChange logger str (J.TextDocumentContentChangeEvent (Just (J.Range (J.Position sl sc) (J.Position fl fc))) _ txt) +applyChange logger str (J.TextDocumentContentChangeEvent (J.InL e)) | J.Range (J.Position sl sc) (J.Position fl fc) <- e .! #range, txt <- e .! #text = changeChars logger str (Rope.Position (fromIntegral sl) (fromIntegral sc)) (Rope.Position (fromIntegral fl) (fromIntegral fc)) txt +applyChange _ _ (J.TextDocumentContentChangeEvent (J.InR e)) + = pure $ Rope.fromText $ e .! #text -- --------------------------------------------------------------------- diff --git a/lsp/test/DiagnosticsSpec.hs b/lsp/test/DiagnosticsSpec.hs index f26346c76..47e3b53ed 100644 --- a/lsp/test/DiagnosticsSpec.hs +++ b/lsp/test/DiagnosticsSpec.hs @@ -7,7 +7,7 @@ import qualified Data.HashMap.Strict as HM import qualified Data.SortedList as SL import Data.Text (Text) import Language.LSP.Diagnostics -import qualified Language.LSP.Types as J +import qualified Language.LSP.Types as LSP import Test.Hspec @@ -29,20 +29,20 @@ spec = describe "Diagnostics functions" diagnosticsSpec -- --------------------------------------------------------------------- -mkDiagnostic :: Maybe J.DiagnosticSource -> Text -> J.Diagnostic +mkDiagnostic :: Maybe Text -> Text -> LSP.Diagnostic mkDiagnostic ms str = let - rng = J.Range (J.Position 0 1) (J.Position 3 0) - loc = J.Location (J.Uri "file") rng + rng = LSP.Range (LSP.Position 0 1) (LSP.Position 3 0) + loc = LSP.Location (LSP.Uri "file") rng in - J.Diagnostic rng Nothing Nothing ms str Nothing (Just (J.List [J.DiagnosticRelatedInformation loc str])) + LSP.Diagnostic rng Nothing Nothing Nothing ms str Nothing (Just [LSP.DiagnosticRelatedInformation loc str]) Nothing -mkDiagnostic2 :: Maybe J.DiagnosticSource -> Text -> J.Diagnostic +mkDiagnostic2 :: Maybe Text -> Text -> LSP.Diagnostic mkDiagnostic2 ms str = let - rng = J.Range (J.Position 4 1) (J.Position 5 0) - loc = J.Location (J.Uri "file") rng - in J.Diagnostic rng Nothing Nothing ms str Nothing (Just (J.List [J.DiagnosticRelatedInformation loc str])) + rng = LSP.Range (LSP.Position 4 1) (LSP.Position 5 0) + loc = LSP.Location (LSP.Uri "file") rng + in LSP.Diagnostic rng Nothing Nothing Nothing ms str Nothing (Just [LSP.DiagnosticRelatedInformation loc str]) Nothing -- --------------------------------------------------------------------- @@ -55,7 +55,7 @@ diagnosticsSpec = do [ mkDiagnostic (Just "hlint") "a" , mkDiagnostic (Just "hlint") "b" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" (updateDiagnostics HM.empty uri Nothing (partitionBySource diags)) `shouldBe` HM.fromList [ (uri,StoreItem Nothing $ Map.fromList [(Just "hlint", SL.toSortedList diags) ] ) @@ -69,7 +69,7 @@ diagnosticsSpec = do [ mkDiagnostic (Just "hlint") "a" , mkDiagnostic (Just "ghcmod") "b" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" (updateDiagnostics HM.empty uri Nothing (partitionBySource diags)) `shouldBe` HM.fromList [ (uri,StoreItem Nothing $ Map.fromList @@ -86,7 +86,7 @@ diagnosticsSpec = do [ mkDiagnostic (Just "hlint") "a" , mkDiagnostic (Just "ghcmod") "b" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" (updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags)) `shouldBe` HM.fromList [ (uri,StoreItem (Just 1) $ Map.fromList @@ -107,7 +107,7 @@ diagnosticsSpec = do diags2 = [ mkDiagnostic (Just "hlint") "a2" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let origStore = updateDiagnostics HM.empty uri Nothing (partitionBySource diags1) (updateDiagnostics origStore uri Nothing (partitionBySource diags2)) `shouldBe` HM.fromList @@ -125,7 +125,7 @@ diagnosticsSpec = do diags2 = [ mkDiagnostic (Just "hlint") "a2" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let origStore = updateDiagnostics HM.empty uri Nothing (partitionBySource diags1) (updateDiagnostics origStore uri Nothing (partitionBySource diags2)) `shouldBe` HM.fromList @@ -143,7 +143,7 @@ diagnosticsSpec = do [ mkDiagnostic (Just "hlint") "a1" , mkDiagnostic (Just "ghcmod") "b1" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let origStore = updateDiagnostics HM.empty uri Nothing (partitionBySource diags1) (updateDiagnostics origStore uri Nothing (Map.fromList [(Just "ghcmod",SL.toSortedList [])])) `shouldBe` HM.fromList @@ -166,7 +166,7 @@ diagnosticsSpec = do diags2 = [ mkDiagnostic (Just "hlint") "a2" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let origStore = updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags1) (updateDiagnostics origStore uri (Just 2) (partitionBySource diags2)) `shouldBe` HM.fromList @@ -184,7 +184,7 @@ diagnosticsSpec = do diags2 = [ mkDiagnostic (Just "hlint") "a2" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let origStore = updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags1) (updateDiagnostics origStore uri (Just 2) (partitionBySource diags2)) `shouldBe` HM.fromList @@ -203,10 +203,10 @@ diagnosticsSpec = do [ mkDiagnostic (Just "hlint") "a" , mkDiagnostic (Just "ghcmod") "b" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let ds = updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags) getDiagnosticParamsFor 10 ds uri `shouldBe` - Just (J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (Just 1) (J.List $ reverse diags)) + Just (LSP.PublishDiagnosticsParams (LSP.fromNormalizedUri uri) (Just 1) (reverse diags)) -- --------------------------------- @@ -220,20 +220,20 @@ diagnosticsSpec = do , mkDiagnostic (Just "hlint") "c" , mkDiagnostic (Just "ghcmod") "d" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let ds = updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags) getDiagnosticParamsFor 2 ds uri `shouldBe` - Just (J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (Just 1) - (J.List [ - mkDiagnostic (Just "ghcmod") "d" - , mkDiagnostic (Just "hlint") "c" - ])) + Just (LSP.PublishDiagnosticsParams (LSP.fromNormalizedUri uri) (Just 1) + [ + mkDiagnostic (Just "ghcmod") "d" + , mkDiagnostic (Just "hlint") "c" + ]) getDiagnosticParamsFor 1 ds uri `shouldBe` - Just (J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (Just 1) - (J.List [ - mkDiagnostic (Just "ghcmod") "d" - ])) + Just (LSP.PublishDiagnosticsParams (LSP.fromNormalizedUri uri) (Just 1) + [ + mkDiagnostic (Just "ghcmod") "d" + ]) -- --------------------------------- @@ -247,23 +247,23 @@ diagnosticsSpec = do , mkDiagnostic (Just "hlint") "c" , mkDiagnostic (Just "ghcmod") "d" ] - uri = J.toNormalizedUri $ J.Uri "uri" + uri = LSP.toNormalizedUri $ LSP.Uri "uri" let ds = updateDiagnostics HM.empty uri (Just 1) (partitionBySource diags) getDiagnosticParamsFor 100 ds uri `shouldBe` - Just (J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (Just 1) - (J.List [ - mkDiagnostic (Just "ghcmod") "d" - , mkDiagnostic (Just "hlint") "c" - , mkDiagnostic2 (Just "ghcmod") "b" - , mkDiagnostic2 (Just "hlint") "a" - ])) + Just (LSP.PublishDiagnosticsParams (LSP.fromNormalizedUri uri) (Just 1) + [ + mkDiagnostic (Just "ghcmod") "d" + , mkDiagnostic (Just "hlint") "c" + , mkDiagnostic2 (Just "ghcmod") "b" + , mkDiagnostic2 (Just "hlint") "a" + ]) let ds' = flushBySource ds (Just "hlint") getDiagnosticParamsFor 100 ds' uri `shouldBe` - Just (J.PublishDiagnosticsParams (J.fromNormalizedUri uri) (Just 1) - (J.List [ - mkDiagnostic (Just "ghcmod") "d" - , mkDiagnostic2 (Just "ghcmod") "b" - ])) + Just (LSP.PublishDiagnosticsParams (LSP.fromNormalizedUri uri) (Just 1) + [ + mkDiagnostic (Just "ghcmod") "d" + , mkDiagnostic2 (Just "ghcmod") "b" + ]) -- --------------------------------- diff --git a/lsp/test/VspSpec.hs b/lsp/test/VspSpec.hs index 7e24cb457..f5037ea1c 100644 --- a/lsp/test/VspSpec.hs +++ b/lsp/test/VspSpec.hs @@ -1,6 +1,8 @@ {-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE OverloadedLabels #-} module VspSpec where +import Data.Row import Data.String import qualified Data.Text.Utf16.Rope as Rope import Language.LSP.VFS @@ -31,23 +33,27 @@ vfsFromText text = VirtualFile 0 0 (Rope.fromText text) -- --------------------------------------------------------------------- +mkChangeEvent :: J.Range -> T.Text -> J.TextDocumentContentChangeEvent +mkChangeEvent r t = J.TextDocumentContentChangeEvent $ J.InL $ #range .== r .+ #rangeLength .== Nothing .+ #text .== t + vspSpec :: Spec vspSpec = do describe "applys changes in order" $ do it "handles vscode style undos" $ do let orig = "abc" changes = - [ J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 2 0 3) Nothing "" - , J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 1 0 2) Nothing "" - , J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 0 0 1) Nothing "" + [ mkChangeEvent (J.mkRange 0 2 0 3) "" + , mkChangeEvent (J.mkRange 0 1 0 2) "" + , mkChangeEvent (J.mkRange 0 0 0 1) "" ] applyChanges mempty orig changes `shouldBe` Identity "" it "handles vscode style redos" $ do let orig = "" changes = - [ J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 1 0 1) Nothing "a" - , J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 2 0 2) Nothing "b" - , J.TextDocumentContentChangeEvent (Just $ J.mkRange 0 3 0 3) Nothing "c" + [ + mkChangeEvent (J.mkRange 0 1 0 1) "a" + , mkChangeEvent (J.mkRange 0 2 0 2) "b" + , mkChangeEvent (J.mkRange 0 3 0 3) "c" ] applyChanges mempty orig changes `shouldBe` Identity "abc" @@ -63,25 +69,7 @@ vspSpec = do , "-- fooo" , "foo :: Int" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 2 1 2 5) (Just 4) "" - Rope.lines <$> new `shouldBe` Identity - [ "abcdg" - , "module Foo where" - , "-oo" - , "foo :: Int" - ] - - it "deletes characters within a line (no len)" $ do - let - orig = unlines - [ "abcdg" - , "module Foo where" - , "-- fooo" - , "foo :: Int" - ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 2 1 2 5) Nothing "" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 2 1 2 5) "" Rope.lines <$> new `shouldBe` Identity [ "abcdg" , "module Foo where" @@ -100,30 +88,13 @@ vspSpec = do , "-- fooo" , "foo :: Int" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 2 0 3 0) (Just 8) "" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 2 0 3 0) "" Rope.lines <$> new `shouldBe` Identity [ "abcdg" , "module Foo where" , "foo :: Int" ] - it "deletes one line(no len)" $ do - -- based on vscode log - let - orig = unlines - [ "abcdg" - , "module Foo where" - , "-- fooo" - , "foo :: Int" - ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 2 0 3 0) Nothing "" - Rope.lines <$> new `shouldBe` Identity - [ "abcdg" - , "module Foo where" - , "foo :: Int" - ] -- --------------------------------- it "deletes two lines" $ do @@ -135,28 +106,12 @@ vspSpec = do , "foo :: Int" , "foo = bb" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 1 0 3 0) (Just 19) "" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 1 0 3 0) "" Rope.lines <$> new `shouldBe` Identity [ "module Foo where" , "foo = bb" ] - it "deletes two lines(no len)" $ do - -- based on vscode log - let - orig = unlines - [ "module Foo where" - , "-- fooo" - , "foo :: Int" - , "foo = bb" - ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 1 0 3 0) Nothing "" - Rope.lines <$> new `shouldBe` Identity - [ "module Foo where" - , "foo = bb" - ] -- --------------------------------- describe "adds characters" $ do @@ -168,8 +123,7 @@ vspSpec = do , "module Foo where" , "foo :: Int" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 1 16 1 16) (Just 0) "\n-- fooo" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 1 16 1 16) "\n-- fooo" Rope.lines <$> new `shouldBe` Identity [ "abcdg" , "module Foo where" @@ -186,8 +140,7 @@ vspSpec = do [ "module Foo where" , "foo = bb" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 1 8 1 8) Nothing "\n-- fooo\nfoo :: Int" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 1 8 1 8) "\n-- fooo\nfoo :: Int" Rope.lines <$> new `shouldBe` Identity [ "module Foo where" , "foo = bb" @@ -213,36 +166,7 @@ vspSpec = do , " putStrLn \"hello world\"" ] -- new = changeChars (fromString orig) (J.Position 7 0) (J.Position 7 8) "baz =" - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 7 0 7 8) (Just 8) "baz =" - Rope.lines <$> new `shouldBe` Identity - [ "module Foo where" - , "-- fooo" - , "foo :: Int" - , "foo = bb" - , "" - , "bb = 5" - , "" - , "baz =" - , " putStrLn \"hello world\"" - ] - it "removes end of a line(no len)" $ do - -- based on vscode log - let - orig = unlines - [ "module Foo where" - , "-- fooo" - , "foo :: Int" - , "foo = bb" - , "" - , "bb = 5" - , "" - , "baz = do" - , " putStrLn \"hello world\"" - ] - -- new = changeChars (fromString orig) (J.Position 7 0) (J.Position 7 8) "baz =" - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 7 0 7 8) Nothing "baz =" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 7 0 7 8) "baz =" Rope.lines <$> new `shouldBe` Identity [ "module Foo where" , "-- fooo" @@ -260,8 +184,7 @@ vspSpec = do [ "a𐐀b" , "a𐐀b" ] - new = applyChange mempty (fromString orig) - $ J.TextDocumentContentChangeEvent (Just $ J.mkRange 1 0 1 3) (Just 3) "𐐀𐐀" + new = applyChange mempty (fromString orig) $ mkChangeEvent (J.mkRange 1 0 1 3) "𐐀𐐀" Rope.lines <$> new `shouldBe` Identity [ "a𐐀b" , "𐐀𐐀b" diff --git a/nix/sources.json b/nix/sources.json index 55059fb80..7606fad6c 100644 --- a/nix/sources.json +++ b/nix/sources.json @@ -5,10 +5,10 @@ "homepage": "", "owner": "hercules-ci", "repo": "gitignore.nix", - "rev": "5b9e0ff9d3b551234b4f3eb3983744fa354b17f1", - "sha256": "01l4phiqgw9xgaxr6jr456qmww6kzghqrnbc7aiiww3h6db5vw53", + "rev": "bff2832ec341cf30acb3a4d3e2e7f1f7b590116a", + "sha256": "0va0janxvmilm67nbl81gdbpppal4aprxzb25gp9pqvf76ahxsci", "type": "tarball", - "url": "https://github.com/hercules-ci/gitignore.nix/archive/5b9e0ff9d3b551234b4f3eb3983744fa354b17f1.tar.gz", + "url": "https://github.com/hercules-ci/gitignore.nix/archive/bff2832ec341cf30acb3a4d3e2e7f1f7b590116a.tar.gz", "url_template": "https://github.com///archive/.tar.gz" }, "niv": { @@ -17,10 +17,10 @@ "homepage": "https://github.com/nmattia/niv", "owner": "nmattia", "repo": "niv", - "rev": "5830a4dd348d77e39a0f3c4c762ff2663b602d4c", - "sha256": "1d3lsrqvci4qz2hwjrcnd8h5vfkg8aypq3sjd4g3izbc8frwz5sm", + "rev": "945aa20cd077a8eccb1c42e29f225370b9a8d78b", + "sha256": "0qx94wvmaplagiwmrh558iwwr7nhvini40qmlx21myc66z51if32", "type": "tarball", - "url": "https://github.com/nmattia/niv/archive/5830a4dd348d77e39a0f3c4c762ff2663b602d4c.tar.gz", + "url": "https://github.com/nmattia/niv/archive/945aa20cd077a8eccb1c42e29f225370b9a8d78b.tar.gz", "url_template": "https://github.com///archive/.tar.gz" }, "nixpkgs": { @@ -29,10 +29,10 @@ "homepage": "", "owner": "NixOS", "repo": "nixpkgs", - "rev": "5efc8ca954272c4376ac929f4c5ffefcc20551d5", - "sha256": "15xncc1afq8v78acrcv8xbfkd3ii147mv9a55823pdbqffzg0x54", + "rev": "6766fb6503ae1ebebc2a9704c162b2aef351f921", + "sha256": "1a805n9iqlbmffkzq3l6yf2xp74wjaz5pdcp0cfl0rhc179w4lpy", "type": "tarball", - "url": "https://github.com/NixOS/nixpkgs/archive/5efc8ca954272c4376ac929f4c5ffefcc20551d5.tar.gz", + "url": "https://github.com/NixOS/nixpkgs/archive/6766fb6503ae1ebebc2a9704c162b2aef351f921.tar.gz", "url_template": "https://github.com///archive/.tar.gz" } }