Add files using upload-large-folder tool
Browse filesFiles changed (20)
- projects/ui/serena-new/src/solidlsp/language_servers/intelephense.pyAdded+191
- projects/ui/serena-new/src/solidlsp/language_servers/jedi_server.pyAdded+198
- projects/ui/serena-new/src/solidlsp/language_servers/kotlin_language_server.pyAdded+469
- projects/ui/serena-new/src/solidlsp/language_servers/lua_ls.pyAdded+297
- projects/ui/serena-new/src/solidlsp/language_servers/nixd_ls.pyAdded+396
- projects/ui/serena-new/src/solidlsp/language_servers/omnisharp.pyAdded+380
- projects/ui/serena-new/src/solidlsp/language_servers/pyright_server.pyAdded+202
- projects/ui/serena-new/src/solidlsp/language_servers/r_language_server.pyAdded+172
- projects/ui/serena-new/src/solidlsp/language_servers/ruby_lsp.pyAdded+442
- projects/ui/serena-new/src/solidlsp/language_servers/rust_analyzer.pyAdded+639
- projects/ui/serena-new/src/solidlsp/language_servers/solargraph.pyAdded+373
- projects/ui/serena-new/src/solidlsp/language_servers/sourcekit_lsp.pyAdded+358
- projects/ui/serena-new/src/solidlsp/language_servers/terraform_ls.pyAdded+214
- projects/ui/serena-new/src/solidlsp/language_servers/typescript_language_server.pyAdded+253
- projects/ui/serena-new/src/solidlsp/language_servers/vts_language_server.pyAdded+235
- projects/ui/serena-new/src/solidlsp/language_servers/zls.pyAdded+252
- projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_constants.pyAdded+69
- projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_requests.pyAdded+561
- projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_types.pyAdded
- projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/server.pyAdded+122
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191"""Provides PHP specific instantiation of the LanguageServer class using Intelephense."""
import loggingimport osimport pathlibimport shutilfrom time import sleep
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import PlatformId, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import DefinitionParams, InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
from .common import RuntimeDependency, RuntimeDependencyCollection
class Intelephense(SolidLanguageServer): """ Provides PHP specific instantiation of the LanguageServer class using Intelephense. """
@override def is_ignored_dirname(self, dirname: str) -> bool: # For PHP projects, we should ignore: # - vendor: third-party dependencies managed by Composer # - node_modules: if the project has JavaScript components # - cache: commonly used for caching return super().is_ignored_dirname(dirname) or dirname in ["node_modules", "vendor", "cache"]
@classmethod def _setup_runtime_dependencies( cls, logger: LanguageServerLogger, config: LanguageServerConfig, solidlsp_settings: SolidLSPSettings ) -> str: """ Setup runtime dependencies for Intelephense and return the command to start the server. """ platform_id = PlatformUtils.get_platform_id()
valid_platforms = [ PlatformId.LINUX_x64, PlatformId.LINUX_arm64, PlatformId.OSX, PlatformId.OSX_x64, PlatformId.OSX_arm64, PlatformId.WIN_x64, PlatformId.WIN_arm64, ] assert platform_id in valid_platforms, f"Platform {platform_id} is not supported for multilspy PHP at the moment"
# Verify both node and npm are installed is_node_installed = shutil.which("node") is not None assert is_node_installed, "node is not installed or isn't in PATH. Please install NodeJS and try again." is_npm_installed = shutil.which("npm") is not None assert is_npm_installed, "npm is not installed or isn't in PATH. Please install npm and try again."
# Install intelephense if not already installed intelephense_ls_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "php-lsp") os.makedirs(intelephense_ls_dir, exist_ok=True) intelephense_executable_path = os.path.join(intelephense_ls_dir, "node_modules", ".bin", "intelephense") if not os.path.exists(intelephense_executable_path): deps = RuntimeDependencyCollection( [ RuntimeDependency( id="intelephense", command="npm install --prefix ./ intelephense@1.14.4", platform_id="any", ) ] ) deps.install(logger, intelephense_ls_dir)
assert os.path.exists( intelephense_executable_path ), f"intelephense executable not found at {intelephense_executable_path}, something went wrong."
return f"{intelephense_executable_path} --stdio"
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): # Setup runtime dependencies before initializing intelephense_cmd = self._setup_runtime_dependencies(logger, config, solidlsp_settings)
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=intelephense_cmd, cwd=repository_root_path), "php", solidlsp_settings, ) self.request_id = 0
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Intelephense Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "definition": {"dynamicRegistration": True}, }, "workspace": {"workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}}, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], }
# Add license key if provided via environment variable license_key = os.environ.get("INTELEPHENSE_LICENSE_KEY") if license_key: initialize_params["initializationOptions"] = {"licenceKey": license_key}
return initialize_params
def _start_server(self): """Start Intelephense server process"""
def register_capability_handler(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting Intelephense server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params) self.logger.log( "After sent initialize params", logging.INFO, )
# Verify server capabilities assert "textDocumentSync" in init_response["capabilities"] assert "completionProvider" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"]
self.server.notify.initialized({}) self.completions_available.set()
# Intelephense server is typically ready immediately after initialization # TODO: This is probably incorrect; the server does send an initialized notification, which we could wait for!
@override # For some reason, the LS may need longer to process this, so we just retry def _send_references_request(self, relative_file_path: str, line: int, column: int): # TODO: The LS doesn't return references contained in other files if it doesn't sleep. This is # despite the LS having processed requests already. I don't know what causes this, but sleeping # one second helps. It may be that sleeping only once is enough but that's hard to reliably test. # May be related to the time it takes to read the files or something like that. # The sleeping doesn't seem to be needed on all systems sleep(1) return super()._send_references_request(relative_file_path, line, column)
@override def _send_definition_request(self, definition_params: DefinitionParams): # TODO: same as above, also only a problem if the definition is in another file sleep(1) return super()._send_definition_request(definition_params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198"""Provides Python specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Python."""
import loggingimport osimport pathlib
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class JediServer(SolidLanguageServer): """ Provides Python specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Python. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a JediServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd="jedi-language-server", cwd=repository_root_path), "python", solidlsp_settings, )
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in ["venv", "__pycache__"]
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Jedi Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "processId": os.getpid(), "clientInfo": {"name": "Serena", "version": "0.1.0"}, "locale": "en", "rootPath": repository_absolute_path, "rootUri": root_uri, # Note: this is not necessarily the minimal set of capabilities... "capabilities": { "workspace": { "applyEdit": True, "workspaceEdit": { "documentChanges": True, "resourceOperations": ["create", "rename", "delete"], "failureHandling": "textOnlyTransactional", "normalizesLineEndings": True, "changeAnnotationSupport": {"groupsOnLabel": True}, }, "configuration": True, "didChangeWatchedFiles": {"dynamicRegistration": True, "relativePatternSupport": True}, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "tagSupport": {"valueSet": [1]}, "resolveSupport": {"properties": ["location.range"]}, }, "workspaceFolders": True, "fileOperations": { "dynamicRegistration": True, "didCreate": True, "didRename": True, "didDelete": True, "willCreate": True, "willRename": True, "willDelete": True, }, "inlineValue": {"refreshSupport": True}, "inlayHint": {"refreshSupport": True}, "diagnostics": {"refreshSupport": True}, }, "textDocument": { "publishDiagnostics": { "relatedInformation": True, "versionSupport": False, "tagSupport": {"valueSet": [1, 2]}, "codeDescriptionSupport": True, "dataSupport": True, }, "synchronization": {"dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True, "didSave": True}, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, "activeParameterSupport": True, }, "contextSupport": True, }, "definition": {"dynamicRegistration": True, "linkSupport": True}, "references": {"dynamicRegistration": True}, "documentHighlight": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "hierarchicalDocumentSymbolSupport": True, "tagSupport": {"valueSet": [1]}, "labelSupport": True, }, "documentLink": {"dynamicRegistration": True, "tooltipSupport": True}, "typeDefinition": {"dynamicRegistration": True, "linkSupport": True}, "implementation": {"dynamicRegistration": True, "linkSupport": True}, "declaration": {"dynamicRegistration": True, "linkSupport": True}, "selectionRange": {"dynamicRegistration": True}, "callHierarchy": {"dynamicRegistration": True}, "linkedEditingRange": {"dynamicRegistration": True}, "typeHierarchy": {"dynamicRegistration": True}, "inlineValue": {"dynamicRegistration": True}, "inlayHint": { "dynamicRegistration": True, "resolveSupport": {"properties": ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"]}, }, "diagnostic": {"dynamicRegistration": True, "relatedDocumentSupport": False}, }, "notebookDocument": {"synchronization": {"dynamicRegistration": True, "executionSummarySupport": True}}, "experimental": { "serverStatusNotification": True, "openServerLogs": True, }, }, # See https://github.com/pappasam/jedi-language-server?tab=readme-ov-file # We use the default options except for maxSymbols, where 0 means no limit "initializationOptions": { "workspace": { "symbols": {"ignoreFolders": [".nox", ".tox", ".venv", "__pycache__", "venv"], "maxSymbols": 0}, }, }, "trace": "verbose", "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the JEDI Language Server """
def execute_client_command_handler(params): return []
def do_nothing(params): return
def check_experimental_status(params): if params["quiescent"] == True: self.completions_available.set()
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
self.server.on_request("client/registerCapability", do_nothing) self.server.on_notification("language/status", do_nothing) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status)
self.logger.log("Starting jedi-language-server server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params) assert init_response["capabilities"]["textDocumentSync"]["change"] == 2 assert "completionProvider" in init_response["capabilities"] assert init_response["capabilities"]["completionProvider"] == { "triggerCharacters": [".", "'", '"'], "resolveProvider": True, }
self.server.notify.initialized({})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469"""Provides Kotlin specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Kotlin."""
import dataclassesimport loggingimport osimport pathlibimport stat
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import FileUtils, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
@dataclasses.dataclassclass KotlinRuntimeDependencyPaths: """ Stores the paths to the runtime dependencies of Kotlin Language Server """
java_path: str java_home_path: str kotlin_executable_path: str
class KotlinLanguageServer(SolidLanguageServer): """ Provides Kotlin specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Kotlin. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a Kotlin Language Server instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ runtime_dependency_paths = self._setup_runtime_dependencies(logger, config, solidlsp_settings) self.runtime_dependency_paths = runtime_dependency_paths
# Create command to execute the Kotlin Language Server script cmd = [self.runtime_dependency_paths.kotlin_executable_path, "--stdio"]
# Set environment variables including JAVA_HOME proc_env = {"JAVA_HOME": self.runtime_dependency_paths.java_home_path}
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=cmd, env=proc_env, cwd=repository_root_path), "kotlin", solidlsp_settings, )
@classmethod def _setup_runtime_dependencies( cls, logger: LanguageServerLogger, config: LanguageServerConfig, solidlsp_settings: SolidLSPSettings ) -> KotlinRuntimeDependencyPaths: """ Setup runtime dependencies for Kotlin Language Server and return the paths. """ platform_id = PlatformUtils.get_platform_id()
# Verify platform support assert ( platform_id.value.startswith("win-") or platform_id.value.startswith("linux-") or platform_id.value.startswith("osx-") ), "Only Windows, Linux and macOS platforms are supported for Kotlin in multilspy at the moment"
# Runtime dependency information runtime_dependencies = { "runtimeDependency": { "id": "KotlinLsp", "description": "Kotlin Language Server", "url": "https://download-cdn.jetbrains.com/kotlin-lsp/0.253.10629/kotlin-0.253.10629.zip", "archiveType": "zip", }, "java": { "win-x64": { "url": "https://github.com/redhat-developer/vscode-java/releases/download/v1.42.0/java-win32-x64-1.42.0-561.vsix", "archiveType": "zip", "java_home_path": "extension/jre/21.0.7-win32-x86_64", "java_path": "extension/jre/21.0.7-win32-x86_64/bin/java.exe", }, "linux-x64": { "url": "https://github.com/redhat-developer/vscode-java/releases/download/v1.42.0/java-linux-x64-1.42.0-561.vsix", "archiveType": "zip", "java_home_path": "extension/jre/21.0.7-linux-x86_64", "java_path": "extension/jre/21.0.7-linux-x86_64/bin/java", }, "linux-arm64": { "url": "https://github.com/redhat-developer/vscode-java/releases/download/v1.42.0/java-linux-arm64-1.42.0-561.vsix", "archiveType": "zip", "java_home_path": "extension/jre/21.0.7-linux-aarch64", "java_path": "extension/jre/21.0.7-linux-aarch64/bin/java", }, "osx-x64": { "url": "https://github.com/redhat-developer/vscode-java/releases/download/v1.42.0/java-darwin-x64-1.42.0-561.vsix", "archiveType": "zip", "java_home_path": "extension/jre/21.0.7-macosx-x86_64", "java_path": "extension/jre/21.0.7-macosx-x86_64/bin/java", }, "osx-arm64": { "url": "https://github.com/redhat-developer/vscode-java/releases/download/v1.42.0/java-darwin-arm64-1.42.0-561.vsix", "archiveType": "zip", "java_home_path": "extension/jre/21.0.7-macosx-aarch64", "java_path": "extension/jre/21.0.7-macosx-aarch64/bin/java", }, }, }
kotlin_dependency = runtime_dependencies["runtimeDependency"] java_dependency = runtime_dependencies["java"][platform_id.value]
# Setup paths for dependencies static_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "kotlin_language_server") os.makedirs(static_dir, exist_ok=True)
# Setup Java paths java_dir = os.path.join(static_dir, "java") os.makedirs(java_dir, exist_ok=True)
java_home_path = os.path.join(java_dir, java_dependency["java_home_path"]) java_path = os.path.join(java_dir, java_dependency["java_path"])
# Download and extract Java if not exists if not os.path.exists(java_path): logger.log(f"Downloading Java for {platform_id.value}...", logging.INFO) FileUtils.download_and_extract_archive(logger, java_dependency["url"], java_dir, java_dependency["archiveType"]) # Make Java executable if not platform_id.value.startswith("win-"): os.chmod(java_path, 0o755)
assert os.path.exists(java_path), f"Java executable not found at {java_path}"
# Setup Kotlin Language Server paths kotlin_ls_dir = static_dir
# Get platform-specific executable script path if platform_id.value.startswith("win-"): kotlin_script = os.path.join(kotlin_ls_dir, "kotlin-lsp.cmd") else: kotlin_script = os.path.join(kotlin_ls_dir, "kotlin-lsp.sh")
# Download and extract Kotlin Language Server if script doesn't exist if not os.path.exists(kotlin_script): logger.log("Downloading Kotlin Language Server...", logging.INFO) FileUtils.download_and_extract_archive(logger, kotlin_dependency["url"], static_dir, kotlin_dependency["archiveType"])
# Make script executable on Unix platforms if os.path.exists(kotlin_script) and not platform_id.value.startswith("win-"): os.chmod( kotlin_script, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH )
# Use script file if os.path.exists(kotlin_script): kotlin_executable_path = kotlin_script logger.log(f"Using Kotlin Language Server script at {kotlin_script}", logging.INFO) else: raise FileNotFoundError(f"Kotlin Language Server script not found at {kotlin_script}")
return KotlinRuntimeDependencyPaths( java_path=java_path, java_home_path=java_home_path, kotlin_executable_path=kotlin_executable_path )
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Kotlin Language Server. """ if not os.path.isabs(repository_absolute_path): repository_absolute_path = os.path.abspath(repository_absolute_path)
root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "clientInfo": {"name": "Multilspy Kotlin Client", "version": "1.0.0"}, "locale": "en", "rootPath": repository_absolute_path, "rootUri": root_uri, "capabilities": { "workspace": { "applyEdit": True, "workspaceEdit": { "documentChanges": True, "resourceOperations": ["create", "rename", "delete"], "failureHandling": "textOnlyTransactional", "normalizesLineEndings": True, "changeAnnotationSupport": {"groupsOnLabel": True}, }, "didChangeConfiguration": {"dynamicRegistration": True}, "didChangeWatchedFiles": {"dynamicRegistration": True, "relativePatternSupport": True}, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "tagSupport": {"valueSet": [1]}, "resolveSupport": {"properties": ["location.range"]}, }, "codeLens": {"refreshSupport": True}, "executeCommand": {"dynamicRegistration": True}, "configuration": True, "workspaceFolders": True, "semanticTokens": {"refreshSupport": True}, "fileOperations": { "dynamicRegistration": True, "didCreate": True, "didRename": True, "didDelete": True, "willCreate": True, "willRename": True, "willDelete": True, }, "inlineValue": {"refreshSupport": True}, "inlayHint": {"refreshSupport": True}, "diagnostics": {"refreshSupport": True}, }, "textDocument": { "publishDiagnostics": { "relatedInformation": True, "versionSupport": False, "tagSupport": {"valueSet": [1, 2]}, "codeDescriptionSupport": True, "dataSupport": True, }, "synchronization": {"dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True, "didSave": True}, "completion": { "dynamicRegistration": True, "contextSupport": True, "completionItem": { "snippetSupport": False, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, "tagSupport": {"valueSet": [1]}, "insertReplaceSupport": False, "resolveSupport": {"properties": ["documentation", "detail", "additionalTextEdits"]}, "insertTextModeSupport": {"valueSet": [1, 2]}, "labelDetailsSupport": True, }, "insertTextMode": 2, "completionItemKind": { "valueSet": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] }, "completionList": {"itemDefaults": ["commitCharacters", "editRange", "insertTextFormat", "insertTextMode"]}, }, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, "activeParameterSupport": True, }, "contextSupport": True, }, "definition": {"dynamicRegistration": True, "linkSupport": True}, "references": {"dynamicRegistration": True}, "documentHighlight": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "hierarchicalDocumentSymbolSupport": True, "tagSupport": {"valueSet": [1]}, "labelSupport": True, }, "codeAction": { "dynamicRegistration": True, "isPreferredSupport": True, "disabledSupport": True, "dataSupport": True, "resolveSupport": {"properties": ["edit"]}, "codeActionLiteralSupport": { "codeActionKind": { "valueSet": [ "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports", ] } }, "honorsChangeAnnotations": False, }, "codeLens": {"dynamicRegistration": True}, "formatting": {"dynamicRegistration": True}, "rangeFormatting": {"dynamicRegistration": True}, "onTypeFormatting": {"dynamicRegistration": True}, "rename": { "dynamicRegistration": True, "prepareSupport": True, "prepareSupportDefaultBehavior": 1, "honorsChangeAnnotations": True, }, "documentLink": {"dynamicRegistration": True, "tooltipSupport": True}, "typeDefinition": {"dynamicRegistration": True, "linkSupport": True}, "implementation": {"dynamicRegistration": True, "linkSupport": True}, "colorProvider": {"dynamicRegistration": True}, "foldingRange": { "dynamicRegistration": True, "rangeLimit": 5000, "lineFoldingOnly": True, "foldingRangeKind": {"valueSet": ["comment", "imports", "region"]}, "foldingRange": {"collapsedText": False}, }, "declaration": {"dynamicRegistration": True, "linkSupport": True}, "selectionRange": {"dynamicRegistration": True}, "callHierarchy": {"dynamicRegistration": True}, "semanticTokens": { "dynamicRegistration": True, "tokenTypes": [ "namespace", "type", "class", "enum", "interface", "struct", "typeParameter", "parameter", "variable", "property", "enumMember", "event", "function", "method", "macro", "keyword", "modifier", "comment", "string", "number", "regexp", "operator", "decorator", ], "tokenModifiers": [ "declaration", "definition", "readonly", "static", "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary", ], "formats": ["relative"], "requests": {"range": True, "full": {"delta": True}}, "multilineTokenSupport": False, "overlappingTokenSupport": False, "serverCancelSupport": True, "augmentsSyntaxTokens": True, }, "linkedEditingRange": {"dynamicRegistration": True}, "typeHierarchy": {"dynamicRegistration": True}, "inlineValue": {"dynamicRegistration": True}, "inlayHint": { "dynamicRegistration": True, "resolveSupport": {"properties": ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"]}, }, "diagnostic": {"dynamicRegistration": True, "relatedDocumentSupport": False}, }, "window": { "showMessage": {"messageActionItem": {"additionalPropertiesSupport": True}}, "showDocument": {"support": True}, "workDoneProgress": True, }, "general": { "staleRequestSupport": { "cancel": True, "retryOnContentModified": [ "textDocument/semanticTokens/full", "textDocument/semanticTokens/range", "textDocument/semanticTokens/full/delta", ], }, "regularExpressions": {"engine": "ECMAScript", "version": "ES2020"}, "markdown": {"parser": "marked", "version": "1.1.0"}, "positionEncodings": ["utf-16"], }, "notebookDocument": {"synchronization": {"dynamicRegistration": True, "executionSummarySupport": True}}, }, "initializationOptions": { "workspaceFolders": [root_uri], "storagePath": None, "codegen": {"enabled": False}, "compiler": {"jvm": {"target": "default"}}, "completion": {"snippets": {"enabled": True}}, "diagnostics": {"enabled": True, "level": 4, "debounceTime": 250}, "scripts": {"enabled": True, "buildScriptsEnabled": True}, "indexing": {"enabled": True}, "externalSources": {"useKlsScheme": False, "autoConvertToKotlin": False}, "inlayHints": {"typeHints": False, "parameterHints": False, "chainedHints": False}, "formatting": { "formatter": "ktfmt", "ktfmt": { "style": "google", "indent": 4, "maxWidth": 100, "continuationIndent": 8, "removeUnusedImports": True, }, }, }, "trace": "verbose", "processId": os.getpid(), "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the Kotlin Language Server """
def execute_client_command_handler(params): return []
def do_nothing(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
self.server.on_request("client/registerCapability", do_nothing) self.server.on_notification("language/status", do_nothing) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing)
self.logger.log("Starting Kotlin server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
capabilities = init_response["capabilities"] assert "textDocumentSync" in capabilities, "Server must support textDocumentSync" assert "hoverProvider" in capabilities, "Server must support hover" assert "completionProvider" in capabilities, "Server must support code completion" assert "signatureHelpProvider" in capabilities, "Server must support signature help" assert "definitionProvider" in capabilities, "Server must support go to definition" assert "referencesProvider" in capabilities, "Server must support find references" assert "documentSymbolProvider" in capabilities, "Server must support document symbols" assert "workspaceSymbolProvider" in capabilities, "Server must support workspace symbols" assert "semanticTokensProvider" in capabilities, "Server must support semantic tokens"
self.server.notify.initialized({}) self.completions_available.set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297"""Provides Lua specific instantiation of the LanguageServer class using lua-language-server."""
import loggingimport osimport pathlibimport platformimport shutilimport tarfileimport threadingimport zipfilefrom pathlib import Path
import requestsfrom overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class LuaLanguageServer(SolidLanguageServer): """ Provides Lua specific instantiation of the LanguageServer class using lua-language-server. """
@override def is_ignored_dirname(self, dirname: str) -> bool: # For Lua projects, we should ignore: # - .luarocks: package manager cache # - lua_modules: local dependencies # - node_modules: if the project has JavaScript components return super().is_ignored_dirname(dirname) or dirname in [".luarocks", "lua_modules", "node_modules", "build", "dist", ".cache"]
@staticmethod def _get_lua_ls_path(): """Get the path to lua-language-server executable.""" # First check if it's in PATH lua_ls = shutil.which("lua-language-server") if lua_ls: return lua_ls
# Check common installation locations home = Path.home() possible_paths = [ home / ".local" / "bin" / "lua-language-server", home / ".serena" / "language_servers" / "lua" / "bin" / "lua-language-server", Path("/usr/local/bin/lua-language-server"), Path("/opt/lua-language-server/bin/lua-language-server"), ]
# Add Windows-specific paths if platform.system() == "Windows": possible_paths.extend( [ home / "AppData" / "Local" / "lua-language-server" / "bin" / "lua-language-server.exe", home / ".serena" / "language_servers" / "lua" / "bin" / "lua-language-server.exe", ] )
for path in possible_paths: if path.exists(): return str(path)
return None
@staticmethod def _download_lua_ls(): """Download and install lua-language-server if not present.""" system = platform.system() machine = platform.machine().lower() lua_ls_version = "3.15.0"
# Map platform and architecture to download URL if system == "Linux": if machine in ["x86_64", "amd64"]: download_name = f"lua-language-server-{lua_ls_version}-linux-x64.tar.gz" elif machine in ["aarch64", "arm64"]: download_name = f"lua-language-server-{lua_ls_version}-linux-arm64.tar.gz" else: raise RuntimeError(f"Unsupported Linux architecture: {machine}") elif system == "Darwin": if machine in ["x86_64", "amd64"]: download_name = f"lua-language-server-{lua_ls_version}-darwin-x64.tar.gz" elif machine in ["arm64", "aarch64"]: download_name = f"lua-language-server-{lua_ls_version}-darwin-arm64.tar.gz" else: raise RuntimeError(f"Unsupported macOS architecture: {machine}") elif system == "Windows": if machine in ["amd64", "x86_64"]: download_name = f"lua-language-server-{lua_ls_version}-win32-x64.zip" else: raise RuntimeError(f"Unsupported Windows architecture: {machine}") else: raise RuntimeError(f"Unsupported operating system: {system}")
download_url = f"https://github.com/LuaLS/lua-language-server/releases/download/{lua_ls_version}/{download_name}"
# Create installation directory install_dir = Path.home() / ".serena" / "language_servers" / "lua" install_dir.mkdir(parents=True, exist_ok=True)
# Download the file print(f"Downloading lua-language-server from {download_url}...") response = requests.get(download_url, stream=True) response.raise_for_status()
# Save and extract download_path = install_dir / download_name with open(download_path, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk)
print(f"Extracting lua-language-server to {install_dir}...") if download_name.endswith(".tar.gz"): with tarfile.open(download_path, "r:gz") as tar: tar.extractall(install_dir) elif download_name.endswith(".zip"): with zipfile.ZipFile(download_path, "r") as zip_ref: zip_ref.extractall(install_dir)
# Clean up download file download_path.unlink()
# Make executable on Unix systems if system != "Windows": lua_ls_path = install_dir / "bin" / "lua-language-server" if lua_ls_path.exists(): lua_ls_path.chmod(0o755) return str(lua_ls_path) else: lua_ls_path = install_dir / "bin" / "lua-language-server.exe" if lua_ls_path.exists(): return str(lua_ls_path)
raise RuntimeError("Failed to find lua-language-server executable after extraction")
@staticmethod def _setup_runtime_dependency(): """ Check if required Lua runtime dependencies are available. Downloads lua-language-server if not present. """ lua_ls_path = LuaLanguageServer._get_lua_ls_path()
if not lua_ls_path: print("lua-language-server not found. Downloading...") lua_ls_path = LuaLanguageServer._download_lua_ls() print(f"lua-language-server installed at: {lua_ls_path}")
return lua_ls_path
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): lua_ls_path = self._setup_runtime_dependency()
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=lua_ls_path, cwd=repository_root_path), "lua", solidlsp_settings, ) self.server_ready = threading.Event() self.request_id = 0
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Lua Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "completion": { "dynamicRegistration": True, "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, }, }, "hover": { "dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"], }, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, }, }, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "configuration": True, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], "initializationOptions": { # Lua Language Server specific options "runtime": { "version": "Lua 5.4", "path": ["?.lua", "?/init.lua"], }, "diagnostics": { "enable": True, "globals": ["vim", "describe", "it", "before_each", "after_each"], # Common globals }, "workspace": { "library": [], # Can be extended with project-specific libraries "checkThirdParty": False, "userThirdParty": [], }, "telemetry": { "enable": False, }, "completion": { "enable": True, "callSnippet": "Both", "keywordSnippet": "Both", }, }, } return initialize_params
def _start_server(self): """Start Lua Language Server process"""
def register_capability_handler(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting Lua Language Server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# Verify server capabilities assert "textDocumentSync" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"] assert "documentSymbolProvider" in init_response["capabilities"] assert "referencesProvider" in init_response["capabilities"]
self.server.notify.initialized({}) self.completions_available.set()
# Lua Language Server is typically ready immediately after initialization self.server_ready.set() self.server_ready.wait()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396"""Provides Nix specific instantiation of the LanguageServer class using nixd (Nix Language Server).
Note: Windows is not supported as Nix itself doesn't support Windows natively."""
import loggingimport osimport pathlibimport platformimport shutilimport subprocessimport threadingfrom pathlib import Path
from overrides import override
from solidlsp import ls_typesfrom solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class NixLanguageServer(SolidLanguageServer): """ Provides Nix specific instantiation of the LanguageServer class using nixd. """
def _extend_nix_symbol_range_to_include_semicolon( self, symbol: ls_types.UnifiedSymbolInformation, file_content: str ) -> ls_types.UnifiedSymbolInformation: """ Extend symbol range to include trailing semicolon for Nix attribute symbols.
nixd provides ranges that exclude semicolons (expression-level), but serena needs statement-level ranges that include semicolons for proper replacement. """ range_info = symbol["range"] end_line = range_info["end"]["line"] end_char = range_info["end"]["character"]
# Split file content into lines lines = file_content.split("\n") if end_line >= len(lines): return symbol
line = lines[end_line]
# Check if there's a semicolon immediately after the current range end if end_char < len(line) and line[end_char] == ";": # Extend range to include the semicolon new_range = {"start": range_info["start"], "end": {"line": end_line, "character": end_char + 1}}
# Create modified symbol with extended range extended_symbol = symbol.copy() extended_symbol["range"] = new_range
# CRITICAL: Also update the location.range if it exists if extended_symbol.get("location"): location = extended_symbol["location"].copy() if "range" in location: location["range"] = new_range.copy() extended_symbol["location"] = location
return extended_symbol
return symbol
@override def request_document_symbols( self, relative_file_path: str, include_body: bool = False ) -> tuple[list[ls_types.UnifiedSymbolInformation], list[ls_types.UnifiedSymbolInformation]]: """ Override to extend Nix symbol ranges to include trailing semicolons.
nixd provides expression-level ranges (excluding semicolons) but serena needs statement-level ranges (including semicolons) for proper symbol replacement. """ # Get symbols from parent implementation all_symbols, root_symbols = super().request_document_symbols(relative_file_path, include_body)
# Get file content for range extension file_content = self.language_server.retrieve_full_file_content(relative_file_path)
# Extend ranges for all symbols recursively def extend_symbol_and_children(symbol: ls_types.UnifiedSymbolInformation) -> ls_types.UnifiedSymbolInformation: # Extend this symbol's range extended = self._extend_nix_symbol_range_to_include_semicolon(symbol, file_content)
# Extend children recursively if extended.get("children"): extended["children"] = [extend_symbol_and_children(child) for child in extended["children"]]
return extended
# Apply range extension to all symbols extended_all_symbols = [extend_symbol_and_children(sym) for sym in all_symbols] extended_root_symbols = [extend_symbol_and_children(sym) for sym in root_symbols]
return extended_all_symbols, extended_root_symbols
@override def is_ignored_dirname(self, dirname: str) -> bool: # For Nix projects, we should ignore: # - result: nix build output symlinks # - result-*: multiple build outputs # - .direnv: direnv cache return super().is_ignored_dirname(dirname) or dirname in ["result", ".direnv"] or dirname.startswith("result-")
@staticmethod def _get_nixd_version(): """Get the installed nixd version or None if not found.""" try: result = subprocess.run(["nixd", "--version"], capture_output=True, text=True, check=False) if result.returncode == 0: # nixd outputs version like: nixd 2.0.0 return result.stdout.strip() except FileNotFoundError: return None return None
@staticmethod def _check_nixd_installed(): """Check if nixd is installed in the system.""" return shutil.which("nixd") is not None
@staticmethod def _get_nixd_path(): """Get the path to nixd executable.""" # First check if it's in PATH nixd_path = shutil.which("nixd") if nixd_path: return nixd_path
# Check common installation locations home = Path.home() possible_paths = [ home / ".local" / "bin" / "nixd", home / ".serena" / "language_servers" / "nixd" / "nixd", home / ".nix-profile" / "bin" / "nixd", Path("/usr/local/bin/nixd"), Path("/run/current-system/sw/bin/nixd"), # NixOS system profile Path("/opt/homebrew/bin/nixd"), # Homebrew on Apple Silicon Path("/usr/local/opt/nixd/bin/nixd"), # Homebrew on Intel Mac ]
# Add Windows-specific paths if platform.system() == "Windows": possible_paths.extend( [ home / "AppData" / "Local" / "nixd" / "nixd.exe", home / ".serena" / "language_servers" / "nixd" / "nixd.exe", ] )
for path in possible_paths: if path.exists(): return str(path)
return None
@staticmethod def _install_nixd_with_nix(): """Install nixd using nix if available.""" # Check if nix is available if not shutil.which("nix"): return None
print("Installing nixd using nix... This may take a few minutes.") try: # Try to install nixd using nix profile result = subprocess.run( ["nix", "profile", "install", "github:nix-community/nixd"], capture_output=True, text=True, check=False, timeout=600, # 10 minute timeout for building )
if result.returncode == 0: # Check if nixd is now in PATH nixd_path = shutil.which("nixd") if nixd_path: print(f"Successfully installed nixd at: {nixd_path}") return nixd_path else: # Try nix-env as fallback result = subprocess.run( ["nix-env", "-iA", "nixpkgs.nixd"], capture_output=True, text=True, check=False, timeout=600, ) if result.returncode == 0: nixd_path = shutil.which("nixd") if nixd_path: print(f"Successfully installed nixd at: {nixd_path}") return nixd_path print(f"Failed to install nixd: {result.stderr}")
except subprocess.TimeoutExpired: print("Nix install timed out after 10 minutes") except Exception as e: print(f"Error installing nixd with nix: {e}")
return None
@staticmethod def _setup_runtime_dependency(): """ Check if required Nix runtime dependencies are available. Attempts to install nixd if not present. """ # First check if Nix is available (nixd needs it at runtime) if not shutil.which("nix"): print("WARNING: Nix is not installed. nixd requires Nix to function properly.") raise RuntimeError("Nix is required for nixd. Please install Nix from https://nixos.org/download.html")
nixd_path = NixLanguageServer._get_nixd_path()
if not nixd_path: print("nixd not found. Attempting to install...")
# Try to install with nix if available nixd_path = NixLanguageServer._install_nixd_with_nix()
if not nixd_path: raise RuntimeError( "nixd (Nix Language Server) is not installed.\n" "Please install nixd using one of the following methods:\n" " - Using Nix flakes: nix profile install github:nix-community/nixd\n" " - From nixpkgs: nix-env -iA nixpkgs.nixd\n" " - On macOS with Homebrew: brew install nixd\n\n" "After installation, make sure 'nixd' is in your PATH." )
# Verify nixd works try: result = subprocess.run([nixd_path, "--version"], capture_output=True, text=True, check=False, timeout=5) if result.returncode != 0: raise RuntimeError(f"nixd failed to run: {result.stderr}") except Exception as e: raise RuntimeError(f"Failed to verify nixd installation: {e}")
return nixd_path
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): nixd_path = self._setup_runtime_dependency()
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=nixd_path, cwd=repository_root_path), "nix", solidlsp_settings, ) self.server_ready = threading.Event() self.request_id = 0
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for nixd. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "completion": { "dynamicRegistration": True, "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, }, }, "hover": { "dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"], }, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, }, }, "codeAction": { "dynamicRegistration": True, "codeActionLiteralSupport": { "codeActionKind": { "valueSet": [ "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports", ] } }, }, "rename": {"dynamicRegistration": True, "prepareSupport": True}, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "configuration": True, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], "initializationOptions": { # nixd specific options "nixpkgs": {"expr": "import <nixpkgs> { }"}, "formatting": {"command": ["nixpkgs-fmt"]}, # or ["alejandra"] or ["nixfmt"] "options": { "enable": True, "target": { "installable": "", # Will be auto-detected from flake.nix if present }, }, }, } return initialize_params
def _start_server(self): """Start nixd server process"""
def register_capability_handler(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting nixd server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# Verify server capabilities assert "textDocumentSync" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"] assert "documentSymbolProvider" in init_response["capabilities"] assert "referencesProvider" in init_response["capabilities"]
self.server.notify.initialized({}) self.completions_available.set()
# nixd server is typically ready immediately after initialization self.server_ready.set() self.server_ready.wait()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380"""Provides C# specific instantiation of the LanguageServer class. Contains various configurations and settings specific to C#."""
import jsonimport loggingimport osimport pathlibimport threadingfrom collections.abc import Iterable
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_exceptions import SolidLSPExceptionfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import DotnetVersion, FileUtils, PlatformId, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
def breadth_first_file_scan(root) -> Iterable[str]: """ This function was obtained from https://stackoverflow.com/questions/49654234/is-there-a-breadth-first-search-option-available-in-os-walk-or-equivalent-py It traverses the directory tree in breadth first order. """ dirs = [root] # while we has dirs to scan while dirs: next_dirs = [] for parent in dirs: # scan each dir for f in os.listdir(parent): # if there is a dir, then save for next ittr # if it is a file then yield it (we'll return later) ff = os.path.join(parent, f) if os.path.isdir(ff): next_dirs.append(ff) else: yield ff
# once we've done all the current dirs then # we set up the next itter as the child dirs # from the current itter. dirs = next_dirs
def find_least_depth_sln_file(root_dir) -> str | None: for filename in breadth_first_file_scan(root_dir): if filename.endswith(".sln"): return filename return None
class OmniSharp(SolidLanguageServer): """ Provides C# specific instantiation of the LanguageServer class. Contains various configurations and settings specific to C#. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates an OmniSharp instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ omnisharp_executable_path, dll_path = self._setup_runtime_dependencies(logger, config, solidlsp_settings)
slnfilename = find_least_depth_sln_file(repository_root_path) if slnfilename is None: logger.log("No *.sln file found in repository", logging.ERROR) raise SolidLSPException("No SLN file found in repository")
cmd = " ".join( [ omnisharp_executable_path, "-lsp", "--encoding", "ascii", "-z", "-s", f'"{slnfilename}"', "--hostPID", str(os.getpid()), "DotNet:enablePackageRestore=false", "--loglevel", "trace", "--plugin", dll_path, "FileOptions:SystemExcludeSearchPatterns:0=**/.git", "FileOptions:SystemExcludeSearchPatterns:1=**/.svn", "FileOptions:SystemExcludeSearchPatterns:2=**/.hg", "FileOptions:SystemExcludeSearchPatterns:3=**/CVS", "FileOptions:SystemExcludeSearchPatterns:4=**/.DS_Store", "FileOptions:SystemExcludeSearchPatterns:5=**/Thumbs.db", "RoslynExtensionsOptions:EnableAnalyzersSupport=true", "FormattingOptions:EnableEditorConfigSupport=true", "RoslynExtensionsOptions:EnableImportCompletion=true", "Sdk:IncludePrereleases=true", "RoslynExtensionsOptions:AnalyzeOpenDocumentsOnly=true", "formattingOptions:useTabs=false", "formattingOptions:tabSize=4", "formattingOptions:indentationSize=4", ] ) super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=cmd, cwd=repository_root_path), "csharp", solidlsp_settings )
self.server_ready = threading.Event() self.definition_available = threading.Event() self.references_available = threading.Event()
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in ["bin", "obj"]
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Omnisharp Language Server. """ with open(os.path.join(os.path.dirname(__file__), "omnisharp", "initialize_params.json"), encoding="utf-8") as f: d = json.load(f)
del d["_description"]
d["processId"] = os.getpid() assert d["rootPath"] == "$rootPath" d["rootPath"] = repository_absolute_path
assert d["rootUri"] == "$rootUri" d["rootUri"] = pathlib.Path(repository_absolute_path).as_uri()
assert d["workspaceFolders"][0]["uri"] == "$uri" d["workspaceFolders"][0]["uri"] = pathlib.Path(repository_absolute_path).as_uri()
assert d["workspaceFolders"][0]["name"] == "$name" d["workspaceFolders"][0]["name"] = os.path.basename(repository_absolute_path)
return d
@classmethod def _setup_runtime_dependencies( cls, logger: LanguageServerLogger, config: LanguageServerConfig, solidlsp_settings: SolidLSPSettings ) -> tuple[str, str]: """ Setup runtime dependencies for OmniSharp. """ platform_id = PlatformUtils.get_platform_id() dotnet_version = PlatformUtils.get_dotnet_version()
with open(os.path.join(os.path.dirname(__file__), "omnisharp", "runtime_dependencies.json"), encoding="utf-8") as f: d = json.load(f) del d["_description"]
assert platform_id in [ PlatformId.LINUX_x64, PlatformId.WIN_x64, ], f"Only linux-x64 and win-x64 platform is supported at the moment but got {platform_id=}" assert dotnet_version in [ DotnetVersion.V6, DotnetVersion.V7, DotnetVersion.V8, DotnetVersion.V9, ], f"Only dotnet version 6-9 are supported at the moment but got {dotnet_version=}"
# TODO: Do away with this assumption # Currently, runtime binaries are not available for .Net 7 and .Net 8. Hence, we assume .Net 6 runtime binaries to be compatible with .Net 7, .Net 8 if dotnet_version in [DotnetVersion.V7, DotnetVersion.V8, DotnetVersion.V9]: dotnet_version = DotnetVersion.V6
runtime_dependencies = d["runtimeDependencies"] runtime_dependencies = [dependency for dependency in runtime_dependencies if dependency["platformId"] == platform_id.value] runtime_dependencies = [ dependency for dependency in runtime_dependencies if "dotnet_version" not in dependency or dependency["dotnet_version"] == dotnet_version.value ] assert len(runtime_dependencies) == 2 runtime_dependencies = { runtime_dependencies[0]["id"]: runtime_dependencies[0], runtime_dependencies[1]["id"]: runtime_dependencies[1], }
assert "OmniSharp" in runtime_dependencies assert "RazorOmnisharp" in runtime_dependencies
omnisharp_ls_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "OmniSharp") if not os.path.exists(omnisharp_ls_dir): os.makedirs(omnisharp_ls_dir) FileUtils.download_and_extract_archive(logger, runtime_dependencies["OmniSharp"]["url"], omnisharp_ls_dir, "zip") omnisharp_executable_path = os.path.join(omnisharp_ls_dir, runtime_dependencies["OmniSharp"]["binaryName"]) assert os.path.exists(omnisharp_executable_path) os.chmod(omnisharp_executable_path, 0o755)
razor_omnisharp_ls_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "RazorOmnisharp") if not os.path.exists(razor_omnisharp_ls_dir): os.makedirs(razor_omnisharp_ls_dir) FileUtils.download_and_extract_archive(logger, runtime_dependencies["RazorOmnisharp"]["url"], razor_omnisharp_ls_dir, "zip") razor_omnisharp_dll_path = os.path.join(razor_omnisharp_ls_dir, runtime_dependencies["RazorOmnisharp"]["dll_path"]) assert os.path.exists(razor_omnisharp_dll_path)
return omnisharp_executable_path, razor_omnisharp_dll_path
def _start_server(self): """ Starts the Omnisharp Language Server """
def register_capability_handler(params): assert "registrations" in params for registration in params["registrations"]: if registration["method"] == "textDocument/definition": self.definition_available.set() if registration["method"] == "textDocument/references": self.references_available.set() if registration["method"] == "textDocument/completion": self.completions_available.set()
def lang_status_handler(params): # TODO: Should we wait for # server -> client: {'jsonrpc': '2.0', 'method': 'language/status', 'params': {'type': 'ProjectStatus', 'message': 'OK'}} # Before proceeding? # if params["type"] == "ServiceReady" and params["message"] == "ServiceReady": # self.service_ready_event.set() pass
def execute_client_command_handler(params): return []
def do_nothing(params): return
def check_experimental_status(params): if params["quiescent"] is True: self.server_ready.set()
def workspace_configuration_handler(params): # TODO: We do not know the appropriate way to handle this request. Should ideally contact the OmniSharp dev team return [ { "RoslynExtensionsOptions": { "EnableDecompilationSupport": False, "EnableAnalyzersSupport": True, "EnableImportCompletion": True, "EnableAsyncCompletion": False, "DocumentAnalysisTimeoutMs": 30000, "DiagnosticWorkersThreadCount": 18, "AnalyzeOpenDocumentsOnly": True, "InlayHintsOptions": { "EnableForParameters": False, "ForLiteralParameters": False, "ForIndexerParameters": False, "ForObjectCreationParameters": False, "ForOtherParameters": False, "SuppressForParametersThatDifferOnlyBySuffix": False, "SuppressForParametersThatMatchMethodIntent": False, "SuppressForParametersThatMatchArgumentName": False, "EnableForTypes": False, "ForImplicitVariableTypes": False, "ForLambdaParameterTypes": False, "ForImplicitObjectCreation": False, }, "LocationPaths": None, }, "FormattingOptions": { "OrganizeImports": False, "EnableEditorConfigSupport": True, "NewLine": "\n", "UseTabs": False, "TabSize": 4, "IndentationSize": 4, "SpacingAfterMethodDeclarationName": False, "SeparateImportDirectiveGroups": False, "SpaceWithinMethodDeclarationParenthesis": False, "SpaceBetweenEmptyMethodDeclarationParentheses": False, "SpaceAfterMethodCallName": False, "SpaceWithinMethodCallParentheses": False, "SpaceBetweenEmptyMethodCallParentheses": False, "SpaceAfterControlFlowStatementKeyword": True, "SpaceWithinExpressionParentheses": False, "SpaceWithinCastParentheses": False, "SpaceWithinOtherParentheses": False, "SpaceAfterCast": False, "SpaceBeforeOpenSquareBracket": False, "SpaceBetweenEmptySquareBrackets": False, "SpaceWithinSquareBrackets": False, "SpaceAfterColonInBaseTypeDeclaration": True, "SpaceAfterComma": True, "SpaceAfterDot": False, "SpaceAfterSemicolonsInForStatement": True, "SpaceBeforeColonInBaseTypeDeclaration": True, "SpaceBeforeComma": False, "SpaceBeforeDot": False, "SpaceBeforeSemicolonsInForStatement": False, "SpacingAroundBinaryOperator": "single", "IndentBraces": False, "IndentBlock": True, "IndentSwitchSection": True, "IndentSwitchCaseSection": True, "IndentSwitchCaseSectionWhenBlock": True, "LabelPositioning": "oneLess", "WrappingPreserveSingleLine": True, "WrappingKeepStatementsOnSingleLine": True, "NewLinesForBracesInTypes": True, "NewLinesForBracesInMethods": True, "NewLinesForBracesInProperties": True, "NewLinesForBracesInAccessors": True, "NewLinesForBracesInAnonymousMethods": True, "NewLinesForBracesInControlBlocks": True, "NewLinesForBracesInAnonymousTypes": True, "NewLinesForBracesInObjectCollectionArrayInitializers": True, "NewLinesForBracesInLambdaExpressionBody": True, "NewLineForElse": True, "NewLineForCatch": True, "NewLineForFinally": True, "NewLineForMembersInObjectInit": True, "NewLineForMembersInAnonymousTypes": True, "NewLineForClausesInQuery": True, }, "FileOptions": { "SystemExcludeSearchPatterns": [ "**/node_modules/**/*", "**/bin/**/*", "**/obj/**/*", "**/.git/**/*", "**/.git", "**/.svn", "**/.hg", "**/CVS", "**/.DS_Store", "**/Thumbs.db", ], "ExcludeSearchPatterns": [], }, "RenameOptions": { "RenameOverloads": False, "RenameInStrings": False, "RenameInComments": False, }, "ImplementTypeOptions": { "InsertionBehavior": 0, "PropertyGenerationBehavior": 0, }, "DotNetCliOptions": {"LocationPaths": None}, "Plugins": {"LocationPaths": None}, } ]
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("language/status", lang_status_handler) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status) self.server.on_request("workspace/configuration", workspace_configuration_handler)
self.logger.log("Starting OmniSharp server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params) self.server.notify.initialized({}) with open(os.path.join(os.path.dirname(__file__), "omnisharp", "workspace_did_change_configuration.json"), encoding="utf-8") as f: self.server.notify.workspace_did_change_configuration({"settings": json.load(f)}) assert "capabilities" in init_response if "definitionProvider" in init_response["capabilities"] and init_response["capabilities"]["definitionProvider"]: self.definition_available.set() if "referencesProvider" in init_response["capabilities"] and init_response["capabilities"]["referencesProvider"]: self.references_available.set()
self.definition_available.wait() self.references_available.wait()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202"""Provides Python specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Python."""
import loggingimport osimport pathlibimport reimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class PyrightServer(SolidLanguageServer): """ Provides Python specific instantiation of the LanguageServer class using Pyright. Contains various configurations and settings specific to Python. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a PyrightServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ super().__init__( config, logger, repository_root_path, # Note 1: we can also use `pyright-langserver --stdio` but it requires pyright to be installed with npm # Note 2: we can also use `bpyright-langserver --stdio` if we ever are unhappy with pyright ProcessLaunchInfo(cmd="python -m pyright.langserver --stdio", cwd=repository_root_path), "python", solidlsp_settings, )
# Event to signal when initial workspace analysis is complete self.analysis_complete = threading.Event() self.found_source_files = False
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in ["venv", "__pycache__"]
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Pyright Language Server. """ # Create basic initialization parameters initialize_params: InitializeParams = { # type: ignore "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": pathlib.Path(repository_absolute_path).as_uri(), "initializationOptions": { "exclude": [ "**/__pycache__", "**/.venv", "**/.env", "**/build", "**/dist", "**/.pixi", ], "reportMissingImports": "error", }, "capabilities": { "workspace": { "workspaceEdit": {"documentChanges": True}, "didChangeConfiguration": {"dynamicRegistration": True}, "didChangeWatchedFiles": {"dynamicRegistration": True}, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "executeCommand": {"dynamicRegistration": True}, }, "textDocument": { "synchronization": {"dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True, "didSave": True}, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, }, }, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "hierarchicalDocumentSymbolSupport": True, }, "publishDiagnostics": {"relatedInformation": True}, }, }, "workspaceFolders": [ {"uri": pathlib.Path(repository_absolute_path).as_uri(), "name": os.path.basename(repository_absolute_path)} ], }
return initialize_params
def _start_server(self): """ Starts the Pyright Language Server and waits for initial workspace analysis to complete.
This prevents zombie processes by ensuring Pyright has finished its initial background tasks before we consider the server ready.
Usage: ``` async with lsp.start_server(): # LanguageServer has been initialized and workspace analysis is complete await lsp.request_definition(...) await lsp.request_references(...) # Shutdown the LanguageServer on exit from scope # LanguageServer has been shutdown cleanly ``` """
def execute_client_command_handler(params): return []
def do_nothing(params): return
def window_log_message(msg): """ Monitor Pyright's log messages to detect when initial analysis is complete. Pyright logs "Found X source files" when it finishes scanning the workspace. """ message_text = msg.get("message", "") self.logger.log(f"LSP: window/logMessage: {message_text}", logging.INFO)
# Look for "Found X source files" which indicates workspace scanning is complete # Unfortunately, pyright is unreliable and there seems to be no better way if re.search(r"Found \d+ source files?", message_text): self.logger.log("Pyright workspace scanning complete", logging.INFO) self.found_source_files = True self.analysis_complete.set() self.completions_available.set()
def check_experimental_status(params): """ Also listen for experimental/serverStatus as a backup signal """ if params.get("quiescent") == True: self.logger.log("Received experimental/serverStatus with quiescent=true", logging.INFO) if not self.found_source_files: self.analysis_complete.set() self.completions_available.set()
# Set up notification handlers self.server.on_request("client/registerCapability", do_nothing) self.server.on_notification("language/status", do_nothing) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status)
self.logger.log("Starting pyright-langserver server process", logging.INFO) self.server.start()
# Send proper initialization parameters initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to pyright server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params) self.logger.log(f"Received initialize response from pyright server: {init_response}", logging.INFO)
# Verify that the server supports our required features assert "textDocumentSync" in init_response["capabilities"] assert "completionProvider" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"]
# Complete the initialization handshake self.server.notify.initialized({})
# Wait for Pyright to complete its initial workspace analysis # This prevents zombie processes by ensuring background tasks finish self.logger.log("Waiting for Pyright to complete initial workspace analysis...", logging.INFO) if self.analysis_complete.wait(timeout=5.0): self.logger.log("Pyright initial analysis complete, server ready", logging.INFO) else: self.logger.log("Timeout waiting for Pyright analysis completion, proceeding anyway", logging.WARNING) # Fallback: assume analysis is complete after timeout self.analysis_complete.set() self.completions_available.set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import loggingimport osimport pathlibimport subprocessimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class RLanguageServer(SolidLanguageServer): """R Language Server implementation using the languageserver R package."""
@override def _get_wait_time_for_cross_file_referencing(self) -> float: return 5.0 # R language server needs extra time for workspace indexing in CI environments
@override def is_ignored_dirname(self, dirname: str) -> bool: # For R projects, ignore common directories return super().is_ignored_dirname(dirname) or dirname in [ "renv", # R environment management "packrat", # Legacy R package management ".Rproj.user", # RStudio project files "vignettes", # Package vignettes (often large) ]
@staticmethod def _check_r_installation(): """Check if R and languageserver are available.""" try: # Check R installation result = subprocess.run(["R", "--version"], capture_output=True, text=True, check=False) if result.returncode != 0: raise RuntimeError("R is not installed or not in PATH")
# Check languageserver package result = subprocess.run( ["R", "--vanilla", "--quiet", "--slave", "-e", "if (!require('languageserver', quietly=TRUE)) quit(status=1)"], capture_output=True, text=True, check=False, )
if result.returncode != 0: raise RuntimeError( "R languageserver package is not installed.\nInstall it with: R -e \"install.packages('languageserver')\"" )
except FileNotFoundError: raise RuntimeError("R is not installed. Please install R from https://www.r-project.org/")
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): # Check R installation self._check_r_installation()
# R command to start language server # Use --vanilla for minimal startup and --quiet to suppress all output except LSP # Set specific options to improve parsing stability r_cmd = 'R --vanilla --quiet --slave -e "options(languageserver.debug_mode = FALSE); languageserver::run()"'
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=r_cmd, cwd=repository_root_path), "r", solidlsp_settings, ) self.server_ready = threading.Event()
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """Initialize params for R Language Server.""" root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "completion": { "dynamicRegistration": True, "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, }, }, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "formatting": {"dynamicRegistration": True}, "rangeFormatting": {"dynamicRegistration": True}, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """Start R Language Server process."""
def window_log_message(msg): self.logger.log(f"R LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
def register_capability_handler(params): return
# Register LSP message handlers self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting R Language Server process", logging.INFO) self.server.start()
initialize_params = self._get_initialize_params(self.repository_root_path) self.logger.log( "Sending initialize request to R Language Server", logging.INFO, )
init_response = self.server.send.initialize(initialize_params)
# Verify server capabilities capabilities = init_response.get("capabilities", {}) assert "textDocumentSync" in capabilities if "completionProvider" in capabilities: self.logger.log("R LSP completion provider available", logging.INFO) if "definitionProvider" in capabilities: self.logger.log("R LSP definition provider available", logging.INFO)
self.server.notify.initialized({}) self.completions_available.set()
# R Language Server is ready after initialization self.server_ready.set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442"""Ruby LSP Language Server implementation using Shopify's ruby-lsp.Provides modern Ruby language server capabilities with improved performance."""
import jsonimport loggingimport osimport pathlibimport shutilimport subprocessimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class RubyLsp(SolidLanguageServer): """ Provides Ruby specific instantiation of the LanguageServer class using ruby-lsp. Contains various configurations and settings specific to Ruby with modern LSP features. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a RubyLsp instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ ruby_lsp_executable = self._setup_runtime_dependencies(logger, config, repository_root_path) super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=ruby_lsp_executable, cwd=repository_root_path), "ruby", solidlsp_settings, ) self.analysis_complete = threading.Event() self.service_ready_event = threading.Event()
# Set timeout for ruby-lsp requests - ruby-lsp is fast self.set_request_timeout(30.0) # 30 seconds for initialization and requests
@override def is_ignored_dirname(self, dirname: str) -> bool: """Override to ignore Ruby-specific directories that cause performance issues.""" ruby_ignored_dirs = [ "vendor", # Ruby vendor directory ".bundle", # Bundler cache "tmp", # Temporary files "log", # Log files "coverage", # Test coverage reports ".yardoc", # YARD documentation cache "doc", # Generated documentation "node_modules", # Node modules (for Rails with JS) "storage", # Active Storage files (Rails) "public/packs", # Webpacker output "public/webpack", # Webpack output "public/assets", # Rails compiled assets ] return super().is_ignored_dirname(dirname) or dirname in ruby_ignored_dirs
@override def _get_wait_time_for_cross_file_referencing(self) -> float: """Override to provide optimal wait time for ruby-lsp cross-file reference resolution.
ruby-lsp typically initializes quickly, but may need a brief moment for cross-file analysis in larger projects. """ return 0.5 # 500ms should be sufficient for ruby-lsp
@staticmethod def _find_executable_with_extensions(executable_name: str) -> str | None: """ Find executable with Windows-specific extensions (.bat, .cmd, .exe) if on Windows. Returns the full path to the executable or None if not found. """ import platform
if platform.system() == "Windows": # Try Windows-specific extensions first for ext in [".bat", ".cmd", ".exe"]: path = shutil.which(f"{executable_name}{ext}") if path: return path # Fall back to default search return shutil.which(executable_name) else: # Unix systems return shutil.which(executable_name)
@staticmethod def _setup_runtime_dependencies(logger: LanguageServerLogger, config: LanguageServerConfig, repository_root_path: str) -> list[str]: """ Setup runtime dependencies for ruby-lsp and return the command list to start the server. Installation strategy: Bundler project > global ruby-lsp > gem install ruby-lsp """ # Check if Ruby is installed try: result = subprocess.run(["ruby", "--version"], check=True, capture_output=True, cwd=repository_root_path, text=True) ruby_version = result.stdout.strip() logger.log(f"Ruby version: {ruby_version}", logging.INFO)
# Extract version number for compatibility checks import re
version_match = re.search(r"ruby (\d+)\.(\d+)\.(\d+)", ruby_version) if version_match: major, minor, patch = map(int, version_match.groups()) if major < 2 or (major == 2 and minor < 6): logger.log(f"Warning: Ruby {major}.{minor}.{patch} detected. ruby-lsp works best with Ruby 2.6+", logging.WARNING)
except subprocess.CalledProcessError as e: error_msg = e.stderr if isinstance(e.stderr, str) else e.stderr.decode() if e.stderr else "Unknown error" raise RuntimeError( f"Error checking Ruby installation: {error_msg}. Please ensure Ruby is properly installed and in PATH." ) from e except FileNotFoundError as e: raise RuntimeError( "Ruby is not installed or not found in PATH. Please install Ruby using one of these methods:\n" " - Using rbenv: rbenv install 3.0.0 && rbenv global 3.0.0\n" " - Using RVM: rvm install 3.0.0 && rvm use 3.0.0 --default\n" " - Using asdf: asdf install ruby 3.0.0 && asdf global ruby 3.0.0\n" " - System package manager (brew install ruby, apt install ruby, etc.)" ) from e
# Check for Bundler project (Gemfile exists) gemfile_path = os.path.join(repository_root_path, "Gemfile") gemfile_lock_path = os.path.join(repository_root_path, "Gemfile.lock") is_bundler_project = os.path.exists(gemfile_path)
if is_bundler_project: logger.log("Detected Bundler project (Gemfile found)", logging.INFO)
# Check if bundle command is available using Windows-compatible search bundle_path = RubyLsp._find_executable_with_extensions("bundle") if not bundle_path: # Try common bundle executables for bundle_cmd in ["bin/bundle", "bundle"]: if bundle_cmd.startswith("bin/"): bundle_full_path = os.path.join(repository_root_path, bundle_cmd) else: bundle_full_path = RubyLsp._find_executable_with_extensions(bundle_cmd) if bundle_full_path and os.path.exists(bundle_full_path): bundle_path = bundle_full_path if bundle_cmd.startswith("bin/") else bundle_cmd break
if not bundle_path: logger.log( "Bundler project detected but 'bundle' command not found. Falling back to global ruby-lsp installation.", logging.WARNING, ) else: # Check if ruby-lsp is in Gemfile.lock ruby_lsp_in_bundle = False if os.path.exists(gemfile_lock_path): try: with open(gemfile_lock_path) as f: content = f.read() ruby_lsp_in_bundle = "ruby-lsp" in content.lower() except Exception as e: logger.log(f"Warning: Could not read Gemfile.lock: {e}", logging.WARNING)
if ruby_lsp_in_bundle: logger.log("Found ruby-lsp in Gemfile.lock", logging.INFO) return [bundle_path, "exec", "ruby-lsp"] else: logger.log( "ruby-lsp not found in Gemfile.lock. Consider adding 'gem \"ruby-lsp\"' to your Gemfile for better compatibility.", logging.INFO, ) # Fall through to global installation check
# Check if ruby-lsp is available globally using Windows-compatible search ruby_lsp_path = RubyLsp._find_executable_with_extensions("ruby-lsp") if ruby_lsp_path: logger.log(f"Found ruby-lsp at: {ruby_lsp_path}", logging.INFO) return [ruby_lsp_path]
# Try to install ruby-lsp globally logger.log("ruby-lsp not found, attempting to install globally...", logging.INFO) try: subprocess.run(["gem", "install", "ruby-lsp"], check=True, capture_output=True, cwd=repository_root_path) logger.log("Successfully installed ruby-lsp globally", logging.INFO) # Find the newly installed ruby-lsp executable ruby_lsp_path = RubyLsp._find_executable_with_extensions("ruby-lsp") return [ruby_lsp_path] if ruby_lsp_path else ["ruby-lsp"] except subprocess.CalledProcessError as e: error_msg = e.stderr if isinstance(e.stderr, str) else e.stderr.decode() if e.stderr else str(e) if is_bundler_project: raise RuntimeError( f"Failed to install ruby-lsp globally: {error_msg}\n" "For Bundler projects, please add 'gem \"ruby-lsp\"' to your Gemfile and run 'bundle install'.\n" "Alternatively, install globally: gem install ruby-lsp" ) from e raise RuntimeError(f"Failed to install ruby-lsp: {error_msg}\nPlease try installing manually: gem install ruby-lsp") from e
@staticmethod def _detect_rails_project(repository_root_path: str) -> bool: """ Detect if this is a Rails project by checking for Rails-specific files. """ rails_indicators = [ "config/application.rb", "config/environment.rb", "app/controllers/application_controller.rb", "Rakefile", ]
for indicator in rails_indicators: if os.path.exists(os.path.join(repository_root_path, indicator)): return True
# Check for Rails in Gemfile gemfile_path = os.path.join(repository_root_path, "Gemfile") if os.path.exists(gemfile_path): try: with open(gemfile_path) as f: content = f.read().lower() if "gem 'rails'" in content or 'gem "rails"' in content: return True except Exception: pass
return False
@staticmethod def _get_ruby_exclude_patterns(repository_root_path: str) -> list[str]: """ Get Ruby and Rails-specific exclude patterns for better performance. """ base_patterns = [ "**/vendor/**", # Ruby vendor directory "**/.bundle/**", # Bundler cache "**/tmp/**", # Temporary files "**/log/**", # Log files "**/coverage/**", # Test coverage reports "**/.yardoc/**", # YARD documentation cache "**/doc/**", # Generated documentation "**/.git/**", # Git directory "**/node_modules/**", # Node modules (for Rails with JS) "**/public/assets/**", # Rails compiled assets ]
# Add Rails-specific patterns if this is a Rails project if RubyLsp._detect_rails_project(repository_root_path): base_patterns.extend( [ "**/app/assets/builds/**", # Rails 7+ CSS builds "**/storage/**", # Active Storage "**/public/packs/**", # Webpacker "**/public/webpack/**", # Webpack ] )
return base_patterns
def _get_initialize_params(self) -> InitializeParams: """ Returns ruby-lsp specific initialization parameters. """ exclude_patterns = self._get_ruby_exclude_patterns(self.repository_root_path)
initialize_params = { "processId": os.getpid(), "rootPath": self.repository_root_path, "rootUri": pathlib.Path(self.repository_root_path).as_uri(), "capabilities": { "workspace": { "workspaceEdit": {"documentChanges": True}, "configuration": True, }, "window": { "workDoneProgress": True, }, "textDocument": { "documentSymbol": { "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "completion": { "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, } }, }, }, "initializationOptions": { # ruby-lsp enables all features by default, so we don't need to specify enabledFeatures "experimentalFeaturesEnabled": False, "featuresConfiguration": {}, "indexing": { "includedPatterns": ["**/*.rb", "**/*.rake", "**/*.ru", "**/*.erb"], "excludedPatterns": exclude_patterns, }, }, }
return initialize_params
def _start_server(self) -> None: """ Starts the ruby-lsp Language Server for Ruby """
def register_capability_handler(params: dict) -> None: assert "registrations" in params for registration in params["registrations"]: self.logger.log(f"Registered capability: {registration['method']}", logging.INFO) return
def lang_status_handler(params: dict) -> None: self.logger.log(f"LSP: language/status: {params}", logging.INFO) if params.get("type") == "ready": self.logger.log("ruby-lsp service is ready.", logging.INFO) self.analysis_complete.set() self.completions_available.set()
def execute_client_command_handler(params: dict) -> list: return []
def do_nothing(params: dict) -> None: return
def window_log_message(msg: dict) -> None: self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def progress_handler(params: dict) -> None: # ruby-lsp sends progress notifications during indexing self.logger.log(f"LSP: $/progress: {params}", logging.DEBUG) if "value" in params: value = params["value"] # Check for completion indicators if value.get("kind") == "end": self.logger.log("ruby-lsp indexing complete ($/progress end)", logging.INFO) self.analysis_complete.set() self.completions_available.set() elif value.get("kind") == "begin": self.logger.log("ruby-lsp indexing started ($/progress begin)", logging.INFO) elif "percentage" in value: percentage = value.get("percentage", 0) self.logger.log(f"ruby-lsp indexing progress: {percentage}%", logging.DEBUG) # Handle direct progress format (fallback) elif "token" in params and "value" in params: token = params.get("token") if isinstance(token, str) and "indexing" in token.lower(): value = params.get("value", {}) if value.get("kind") == "end" or value.get("percentage") == 100: self.logger.log("ruby-lsp indexing complete (token progress)", logging.INFO) self.analysis_complete.set() self.completions_available.set()
def window_work_done_progress_create(params: dict) -> None: """Handle workDoneProgress/create requests from ruby-lsp""" self.logger.log(f"LSP: window/workDoneProgress/create: {params}", logging.DEBUG) return {}
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("language/status", lang_status_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", progress_handler) self.server.on_request("window/workDoneProgress/create", window_work_done_progress_create) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting ruby-lsp server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params()
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) self.logger.log(f"Sending init params: {json.dumps(initialize_params, indent=4)}", logging.INFO) init_response = self.server.send.initialize(initialize_params) self.logger.log(f"Received init response: {init_response}", logging.INFO)
# Verify expected capabilities # Note: ruby-lsp may return textDocumentSync in different formats (number or object) text_document_sync = init_response["capabilities"].get("textDocumentSync") if isinstance(text_document_sync, int): assert text_document_sync in [1, 2], f"Unexpected textDocumentSync value: {text_document_sync}" elif isinstance(text_document_sync, dict): # ruby-lsp returns an object with change property assert "change" in text_document_sync, "textDocumentSync object should have 'change' property"
assert "completionProvider" in init_response["capabilities"]
self.server.notify.initialized({}) # Wait for ruby-lsp to complete its initial indexing # ruby-lsp has fast indexing self.logger.log("Waiting for ruby-lsp to complete initial indexing...", logging.INFO) if self.analysis_complete.wait(timeout=30.0): self.logger.log("ruby-lsp initial indexing complete, server ready", logging.INFO) else: self.logger.log("Timeout waiting for ruby-lsp indexing completion, proceeding anyway", logging.WARNING) # Fallback: assume indexing is complete after timeout self.analysis_complete.set() self.completions_available.set()
def _handle_initialization_response(self, init_response): """ Handle the initialization response from ruby-lsp and validate capabilities. """ if "capabilities" in init_response: capabilities = init_response["capabilities"]
# Validate textDocumentSync (ruby-lsp may return different formats) text_document_sync = capabilities.get("textDocumentSync") if isinstance(text_document_sync, int): assert text_document_sync in [1, 2], f"Unexpected textDocumentSync value: {text_document_sync}" elif isinstance(text_document_sync, dict): # ruby-lsp returns an object with change property assert "change" in text_document_sync, "textDocumentSync object should have 'change' property"
# Log important capabilities important_capabilities = [ "completionProvider", "hoverProvider", "definitionProvider", "referencesProvider", "documentSymbolProvider", "codeActionProvider", "documentFormattingProvider", "semanticTokensProvider", ]
for cap in important_capabilities: if cap in capabilities: self.logger.log(f"ruby-lsp {cap}: available", logging.DEBUG)
# Signal that the service is ready self.service_ready_event.set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639"""Provides Rust specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Rust."""
import loggingimport osimport pathlibimport shutilimport subprocessimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class RustAnalyzer(SolidLanguageServer): """ Provides Rust specific instantiation of the LanguageServer class. Contains various configurations and settings specific to Rust. """
@staticmethod def _get_rustup_version(): """Get installed rustup version or None if not found.""" try: result = subprocess.run(["rustup", "--version"], capture_output=True, text=True, check=False) if result.returncode == 0: return result.stdout.strip() except FileNotFoundError: return None return None
@staticmethod def _get_rust_analyzer_path(): """Get rust-analyzer path via rustup or system PATH.""" # First try rustup try: result = subprocess.run(["rustup", "which", "rust-analyzer"], capture_output=True, text=True, check=False) if result.returncode == 0: return result.stdout.strip() except FileNotFoundError: pass
# Fallback to system PATH return shutil.which("rust-analyzer")
@staticmethod def _ensure_rust_analyzer_installed(): """Ensure rust-analyzer is available, install via rustup if needed.""" path = RustAnalyzer._get_rust_analyzer_path() if path: return path
# Check if rustup is available if not RustAnalyzer._get_rustup_version(): raise RuntimeError( "Neither rust-analyzer nor rustup is installed.\n" "Please install Rust via https://rustup.rs/ or install rust-analyzer separately." )
# Try to install rust-analyzer component result = subprocess.run(["rustup", "component", "add", "rust-analyzer"], check=False, capture_output=True, text=True) if result.returncode != 0: raise RuntimeError(f"Failed to install rust-analyzer via rustup: {result.stderr}")
# Try again after installation path = RustAnalyzer._get_rust_analyzer_path() if not path: raise RuntimeError("rust-analyzer installation succeeded but binary not found in PATH")
return path
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a RustAnalyzer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ rustanalyzer_executable_path = self._ensure_rust_analyzer_installed() logger.log(f"Using rust-analyzer at: {rustanalyzer_executable_path}", logging.INFO)
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=rustanalyzer_executable_path, cwd=repository_root_path), "rust", solidlsp_settings, ) self.server_ready = threading.Event() self.service_ready_event = threading.Event() self.initialize_searcher_command_available = threading.Event() self.resolve_main_method_available = threading.Event()
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in ["target"]
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Rust Analyzer Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "clientInfo": {"name": "Visual Studio Code - Insiders", "version": "1.82.0-insider"}, "locale": "en", "capabilities": { "workspace": { "applyEdit": True, "workspaceEdit": { "documentChanges": True, "resourceOperations": ["create", "rename", "delete"], "failureHandling": "textOnlyTransactional", "normalizesLineEndings": True, "changeAnnotationSupport": {"groupsOnLabel": True}, }, "configuration": True, "didChangeWatchedFiles": {"dynamicRegistration": True, "relativePatternSupport": True}, "symbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "tagSupport": {"valueSet": [1]}, "resolveSupport": {"properties": ["location.range"]}, }, "codeLens": {"refreshSupport": True}, "executeCommand": {"dynamicRegistration": True}, "didChangeConfiguration": {"dynamicRegistration": True}, "workspaceFolders": True, "semanticTokens": {"refreshSupport": True}, "fileOperations": { "dynamicRegistration": True, "didCreate": True, "didRename": True, "didDelete": True, "willCreate": True, "willRename": True, "willDelete": True, }, "inlineValue": {"refreshSupport": True}, "inlayHint": {"refreshSupport": True}, "diagnostics": {"refreshSupport": True}, }, "textDocument": { "publishDiagnostics": { "relatedInformation": True, "versionSupport": False, "tagSupport": {"valueSet": [1, 2]}, "codeDescriptionSupport": True, "dataSupport": True, }, "synchronization": {"dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True, "didSave": True}, "completion": { "dynamicRegistration": True, "contextSupport": True, "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, "tagSupport": {"valueSet": [1]}, "insertReplaceSupport": True, "resolveSupport": {"properties": ["documentation", "detail", "additionalTextEdits"]}, "insertTextModeSupport": {"valueSet": [1, 2]}, "labelDetailsSupport": True, }, "insertTextMode": 2, "completionItemKind": { "valueSet": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] }, "completionList": {"itemDefaults": ["commitCharacters", "editRange", "insertTextFormat", "insertTextMode"]}, }, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": { "dynamicRegistration": True, "signatureInformation": { "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, "activeParameterSupport": True, }, "contextSupport": True, }, "definition": {"dynamicRegistration": True, "linkSupport": True}, "references": {"dynamicRegistration": True}, "documentHighlight": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "symbolKind": {"valueSet": list(range(1, 27))}, "hierarchicalDocumentSymbolSupport": True, "tagSupport": {"valueSet": [1]}, "labelSupport": True, }, "codeAction": { "dynamicRegistration": True, "isPreferredSupport": True, "disabledSupport": True, "dataSupport": True, "resolveSupport": {"properties": ["edit"]}, "codeActionLiteralSupport": { "codeActionKind": { "valueSet": [ "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports", ] } }, "honorsChangeAnnotations": False, }, "codeLens": {"dynamicRegistration": True}, "formatting": {"dynamicRegistration": True}, "rangeFormatting": {"dynamicRegistration": True}, "onTypeFormatting": {"dynamicRegistration": True}, "rename": { "dynamicRegistration": True, "prepareSupport": True, "prepareSupportDefaultBehavior": 1, "honorsChangeAnnotations": True, }, "documentLink": {"dynamicRegistration": True, "tooltipSupport": True}, "typeDefinition": {"dynamicRegistration": True, "linkSupport": True}, "implementation": {"dynamicRegistration": True, "linkSupport": True}, "colorProvider": {"dynamicRegistration": True}, "foldingRange": { "dynamicRegistration": True, "rangeLimit": 5000, "lineFoldingOnly": True, "foldingRangeKind": {"valueSet": ["comment", "imports", "region"]}, "foldingRange": {"collapsedText": False}, }, "declaration": {"dynamicRegistration": True, "linkSupport": True}, "selectionRange": {"dynamicRegistration": True}, "callHierarchy": {"dynamicRegistration": True}, "semanticTokens": { "dynamicRegistration": True, "tokenTypes": [ "namespace", "type", "class", "enum", "interface", "struct", "typeParameter", "parameter", "variable", "property", "enumMember", "event", "function", "method", "macro", "keyword", "modifier", "comment", "string", "number", "regexp", "operator", "decorator", ], "tokenModifiers": [ "declaration", "definition", "readonly", "static", "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary", ], "formats": ["relative"], "requests": {"range": True, "full": {"delta": True}}, "multilineTokenSupport": False, "overlappingTokenSupport": False, "serverCancelSupport": True, "augmentsSyntaxTokens": False, }, "linkedEditingRange": {"dynamicRegistration": True}, "typeHierarchy": {"dynamicRegistration": True}, "inlineValue": {"dynamicRegistration": True}, "inlayHint": { "dynamicRegistration": True, "resolveSupport": {"properties": ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"]}, }, "diagnostic": {"dynamicRegistration": True, "relatedDocumentSupport": False}, }, "window": { "showMessage": {"messageActionItem": {"additionalPropertiesSupport": True}}, "showDocument": {"support": True}, "workDoneProgress": True, }, "general": { "staleRequestSupport": { "cancel": True, "retryOnContentModified": [ "textDocument/semanticTokens/full", "textDocument/semanticTokens/range", "textDocument/semanticTokens/full/delta", ], }, "regularExpressions": {"engine": "ECMAScript", "version": "ES2020"}, "markdown": { "parser": "marked", "version": "1.1.0", "allowedTags": [ "ul", "li", "p", "code", "blockquote", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "em", "pre", "table", "thead", "tbody", "tr", "th", "td", "div", "del", "a", "strong", "br", "img", "span", ], }, "positionEncodings": ["utf-16"], }, "notebookDocument": {"synchronization": {"dynamicRegistration": True, "executionSummarySupport": True}}, "experimental": { "snippetTextEdit": True, "codeActionGroup": True, "hoverActions": True, "serverStatusNotification": True, "colorDiagnosticOutput": True, "openServerLogs": True, "localDocs": True, "commands": { "commands": [ "rust-analyzer.runSingle", "rust-analyzer.debugSingle", "rust-analyzer.showReferences", "rust-analyzer.gotoLocation", "editor.action.triggerParameterHints", ] }, }, }, "initializationOptions": { "cargoRunner": None, "runnables": {"extraEnv": None, "problemMatcher": ["$rustc"], "command": None, "extraArgs": []}, "statusBar": {"clickAction": "openLogs"}, "server": {"path": None, "extraEnv": None}, "trace": {"server": "verbose", "extension": False}, "debug": { "engine": "auto", "sourceFileMap": {"/rustc/<id>": "${env:USERPROFILE}/.rustup/toolchains/<toolchain-id>/lib/rustlib/src/rust"}, "openDebugPane": False, "engineSettings": {}, }, "restartServerOnConfigChange": False, "typing": {"continueCommentsOnNewline": True, "autoClosingAngleBrackets": {"enable": False}}, "diagnostics": { "previewRustcOutput": False, "useRustcErrorCode": False, "disabled": [], "enable": True, "experimental": {"enable": False}, "remapPrefix": {}, "warningsAsHint": [], "warningsAsInfo": [], }, "discoverProjectRunner": None, "showUnlinkedFileNotification": True, "showDependenciesExplorer": True, "assist": {"emitMustUse": False, "expressionFillDefault": "todo"}, "cachePriming": {"enable": True, "numThreads": 0}, "cargo": { "autoreload": True, "buildScripts": { "enable": True, "invocationLocation": "workspace", "invocationStrategy": "per_workspace", "overrideCommand": None, "useRustcWrapper": True, }, "cfgs": {}, "extraArgs": [], "extraEnv": {}, "features": [], "noDefaultFeatures": False, "sysroot": "discover", "sysrootSrc": None, "target": None, "unsetTest": ["core"], }, "checkOnSave": True, "check": { "allTargets": True, "command": "check", "extraArgs": [], "extraEnv": {}, "features": None, "ignore": [], "invocationLocation": "workspace", "invocationStrategy": "per_workspace", "noDefaultFeatures": None, "overrideCommand": None, "targets": None, }, "completion": { "autoimport": {"enable": True}, "autoself": {"enable": True}, "callable": {"snippets": "fill_arguments"}, "fullFunctionSignatures": {"enable": False}, "limit": None, "postfix": {"enable": True}, "privateEditable": {"enable": False}, "snippets": { "custom": { "Arc::new": { "postfix": "arc", "body": "Arc::new(${receiver})", "requires": "std::sync::Arc", "description": "Put the expression into an `Arc`", "scope": "expr", }, "Rc::new": { "postfix": "rc", "body": "Rc::new(${receiver})", "requires": "std::rc::Rc", "description": "Put the expression into an `Rc`", "scope": "expr", }, "Box::pin": { "postfix": "pinbox", "body": "Box::pin(${receiver})", "requires": "std::boxed::Box", "description": "Put the expression into a pinned `Box`", "scope": "expr", }, "Ok": { "postfix": "ok", "body": "Ok(${receiver})", "description": "Wrap the expression in a `Result::Ok`", "scope": "expr", }, "Err": { "postfix": "err", "body": "Err(${receiver})", "description": "Wrap the expression in a `Result::Err`", "scope": "expr", }, "Some": { "postfix": "some", "body": "Some(${receiver})", "description": "Wrap the expression in an `Option::Some`", "scope": "expr", }, } }, }, "files": {"excludeDirs": [], "watcher": "client"}, "highlightRelated": { "breakPoints": {"enable": True}, "closureCaptures": {"enable": True}, "exitPoints": {"enable": True}, "references": {"enable": True}, "yieldPoints": {"enable": True}, }, "hover": { "actions": { "debug": {"enable": True}, "enable": True, "gotoTypeDef": {"enable": True}, "implementations": {"enable": True}, "references": {"enable": False}, "run": {"enable": True}, }, "documentation": {"enable": True, "keywords": {"enable": True}}, "links": {"enable": True}, "memoryLayout": {"alignment": "hexadecimal", "enable": True, "niches": False, "offset": "hexadecimal", "size": "both"}, }, "imports": { "granularity": {"enforce": False, "group": "crate"}, "group": {"enable": True}, "merge": {"glob": True}, "preferNoStd": False, "preferPrelude": False, "prefix": "plain", }, "inlayHints": { "bindingModeHints": {"enable": False}, "chainingHints": {"enable": True}, "closingBraceHints": {"enable": True, "minLines": 25}, "closureCaptureHints": {"enable": False}, "closureReturnTypeHints": {"enable": "never"}, "closureStyle": "impl_fn", "discriminantHints": {"enable": "never"}, "expressionAdjustmentHints": {"enable": "never", "hideOutsideUnsafe": False, "mode": "prefix"}, "lifetimeElisionHints": {"enable": "never", "useParameterNames": False}, "maxLength": 25, "parameterHints": {"enable": True}, "reborrowHints": {"enable": "never"}, "renderColons": True, "typeHints": {"enable": True, "hideClosureInitialization": False, "hideNamedConstructor": False}, }, "interpret": {"tests": False}, "joinLines": {"joinAssignments": True, "joinElseIf": True, "removeTrailingComma": True, "unwrapTrivialBlock": True}, "lens": { "debug": {"enable": True}, "enable": True, "forceCustomCommands": True, "implementations": {"enable": True}, "location": "above_name", "references": { "adt": {"enable": False}, "enumVariant": {"enable": False}, "method": {"enable": False}, "trait": {"enable": False}, }, "run": {"enable": True}, }, "linkedProjects": [], "lru": {"capacity": None, "query": {"capacities": {}}}, "notifications": {"cargoTomlNotFound": True}, "numThreads": None, "procMacro": {"attributes": {"enable": True}, "enable": True, "ignored": {}, "server": None}, "references": {"excludeImports": False}, "rust": {"analyzerTargetDir": None}, "rustc": {"source": None}, "rustfmt": {"extraArgs": [], "overrideCommand": None, "rangeFormatting": {"enable": False}}, "semanticHighlighting": { "doc": {"comment": {"inject": {"enable": True}}}, "nonStandardTokens": True, "operator": {"enable": True, "specialization": {"enable": False}}, "punctuation": {"enable": False, "separate": {"macro": {"bang": False}}, "specialization": {"enable": False}}, "strings": {"enable": True}, }, "signatureInfo": {"detail": "full", "documentation": {"enable": True}}, "workspace": {"symbol": {"search": {"kind": "only_types", "limit": 128, "scope": "workspace"}}}, }, "trace": "verbose", "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the Rust Analyzer Language Server """
def register_capability_handler(params): assert "registrations" in params for registration in params["registrations"]: if registration["method"] == "workspace/executeCommand": self.initialize_searcher_command_available.set() self.resolve_main_method_available.set() return
def lang_status_handler(params): # TODO: Should we wait for # server -> client: {'jsonrpc': '2.0', 'method': 'language/status', 'params': {'type': 'ProjectStatus', 'message': 'OK'}} # Before proceeding? if params["type"] == "ServiceReady" and params["message"] == "ServiceReady": self.service_ready_event.set()
def execute_client_command_handler(params): return []
def do_nothing(params): return
def check_experimental_status(params): if params["quiescent"] == True: self.server_ready.set()
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("language/status", lang_status_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status)
self.logger.log("Starting RustAnalyzer server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params) assert init_response["capabilities"]["textDocumentSync"]["change"] == 2 assert "completionProvider" in init_response["capabilities"] assert init_response["capabilities"]["completionProvider"] == { "resolveProvider": True, "triggerCharacters": [":", ".", "'", "("], "completionItem": {"labelDetailsSupport": True}, } self.server.notify.initialized({}) self.completions_available.set()
self.server_ready.wait()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373"""Provides Ruby specific instantiation of the LanguageServer class using Solargraph.Contains various configurations and settings specific to Ruby."""
import jsonimport loggingimport osimport pathlibimport reimport shutilimport subprocessimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class Solargraph(SolidLanguageServer): """ Provides Ruby specific instantiation of the LanguageServer class using Solargraph. Contains various configurations and settings specific to Ruby. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a Solargraph instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ solargraph_executable_path = self._setup_runtime_dependencies(logger, config, repository_root_path) super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=f"{solargraph_executable_path} stdio", cwd=repository_root_path), "ruby", solidlsp_settings, ) # Override internal language enum for file matching (excludes .erb files) # while keeping LSP languageId as "ruby" for protocol compliance from solidlsp.ls_config import Language
self.language = Language.RUBY_SOLARGRAPH self.analysis_complete = threading.Event() self.service_ready_event = threading.Event() self.initialize_searcher_command_available = threading.Event() self.resolve_main_method_available = threading.Event()
# Set timeout for Solargraph requests - Bundler environments may need more time self.set_request_timeout(120.0) # 120 seconds for initialization and requests
@override def is_ignored_dirname(self, dirname: str) -> bool: ruby_ignored_dirs = [ "vendor", # Ruby vendor directory ".bundle", # Bundler cache "tmp", # Temporary files "log", # Log files "coverage", # Test coverage reports ".yardoc", # YARD documentation cache "doc", # Generated documentation "node_modules", # Node modules (for Rails with JS) "storage", # Active Storage files (Rails) ] return super().is_ignored_dirname(dirname) or dirname in ruby_ignored_dirs
@staticmethod def _setup_runtime_dependencies(logger: LanguageServerLogger, config: LanguageServerConfig, repository_root_path: str) -> str: """ Setup runtime dependencies for Solargraph and return the command to start the server. """ # Check if Ruby is installed try: result = subprocess.run(["ruby", "--version"], check=True, capture_output=True, cwd=repository_root_path, text=True) ruby_version = result.stdout.strip() logger.log(f"Ruby version: {ruby_version}", logging.INFO)
# Extract version number for compatibility checks version_match = re.search(r"ruby (\d+)\.(\d+)\.(\d+)", ruby_version) if version_match: major, minor, patch = map(int, version_match.groups()) if major < 2 or (major == 2 and minor < 6): logger.log(f"Warning: Ruby {major}.{minor}.{patch} detected. Solargraph works best with Ruby 2.6+", logging.WARNING)
except subprocess.CalledProcessError as e: error_msg = e.stderr.decode() if e.stderr else "Unknown error" raise RuntimeError( f"Error checking Ruby installation: {error_msg}. Please ensure Ruby is properly installed and in PATH." ) from e except FileNotFoundError as e: raise RuntimeError( "Ruby is not installed or not found in PATH. Please install Ruby using one of these methods:\n" " - Using rbenv: rbenv install 3.0.0 && rbenv global 3.0.0\n" " - Using RVM: rvm install 3.0.0 && rvm use 3.0.0 --default\n" " - Using asdf: asdf install ruby 3.0.0 && asdf global ruby 3.0.0\n" " - System package manager (brew install ruby, apt install ruby, etc.)" ) from e
# Helper function for Windows-compatible executable search def find_executable_with_extensions(executable_name: str) -> str | None: """Find executable with Windows-specific extensions if on Windows.""" import platform
if platform.system() == "Windows": for ext in [".bat", ".cmd", ".exe"]: path = shutil.which(f"{executable_name}{ext}") if path: return path return shutil.which(executable_name) else: return shutil.which(executable_name)
# Check for Bundler project (Gemfile exists) gemfile_path = os.path.join(repository_root_path, "Gemfile") gemfile_lock_path = os.path.join(repository_root_path, "Gemfile.lock") is_bundler_project = os.path.exists(gemfile_path)
if is_bundler_project: logger.log("Detected Bundler project (Gemfile found)", logging.INFO)
# Check if bundle command is available bundle_path = find_executable_with_extensions("bundle") if not bundle_path: # Try common bundle executables for bundle_cmd in ["bin/bundle", "bundle"]: if bundle_cmd.startswith("bin/"): bundle_full_path = os.path.join(repository_root_path, bundle_cmd) else: bundle_full_path = find_executable_with_extensions(bundle_cmd) if bundle_full_path and os.path.exists(bundle_full_path): bundle_path = bundle_full_path if bundle_cmd.startswith("bin/") else bundle_cmd break
if not bundle_path: raise RuntimeError( "Bundler project detected but 'bundle' command not found. Please install Bundler:\n" " - gem install bundler\n" " - Or use your Ruby version manager's bundler installation\n" " - Ensure the bundle command is in your PATH" )
# Check if solargraph is in Gemfile.lock solargraph_in_bundle = False if os.path.exists(gemfile_lock_path): try: with open(gemfile_lock_path) as f: content = f.read() solargraph_in_bundle = "solargraph" in content.lower() except Exception as e: logger.log(f"Warning: Could not read Gemfile.lock: {e}", logging.WARNING)
if solargraph_in_bundle: logger.log("Found solargraph in Gemfile.lock", logging.INFO) return f"{bundle_path} exec solargraph" else: logger.log( "solargraph not found in Gemfile.lock. Please add 'gem \"solargraph\"' to your Gemfile and run 'bundle install'", logging.WARNING, ) # Fall through to global installation check
# Check if solargraph is installed globally # First, try to find solargraph in PATH (includes asdf shims) with Windows support solargraph_path = find_executable_with_extensions("solargraph") if solargraph_path: logger.log(f"Found solargraph at: {solargraph_path}", logging.INFO) return solargraph_path
# Fallback to gem exec (for non-Bundler projects or when global solargraph not found) if not is_bundler_project: runtime_dependencies = [ { "url": "https://rubygems.org/downloads/solargraph-0.51.1.gem", "installCommand": "gem install solargraph -v 0.51.1", "binaryName": "solargraph", "archiveType": "gem", } ]
dependency = runtime_dependencies[0] try: result = subprocess.run( ["gem", "list", "^solargraph$", "-i"], check=False, capture_output=True, text=True, cwd=repository_root_path ) if result.stdout.strip() == "false": logger.log("Installing Solargraph...", logging.INFO) subprocess.run(dependency["installCommand"].split(), check=True, capture_output=True, cwd=repository_root_path)
return "gem exec solargraph" except subprocess.CalledProcessError as e: error_msg = e.stderr.decode() if e.stderr else str(e) raise RuntimeError( f"Failed to check or install Solargraph: {error_msg}\nPlease try installing manually: gem install solargraph" ) from e else: raise RuntimeError( "This appears to be a Bundler project, but solargraph is not available. " "Please add 'gem \"solargraph\"' to your Gemfile and run 'bundle install'." )
@staticmethod def _detect_rails_project(repository_root_path: str) -> bool: """ Detect if this is a Rails project by checking for Rails-specific files. """ rails_indicators = [ "config/application.rb", "config/environment.rb", "app/controllers/application_controller.rb", "Rakefile", ]
for indicator in rails_indicators: if os.path.exists(os.path.join(repository_root_path, indicator)): return True
# Check for Rails in Gemfile gemfile_path = os.path.join(repository_root_path, "Gemfile") if os.path.exists(gemfile_path): try: with open(gemfile_path) as f: content = f.read().lower() if "gem 'rails'" in content or 'gem "rails"' in content: return True except Exception: pass
return False
@staticmethod def _get_ruby_exclude_patterns(repository_root_path: str) -> list[str]: """ Get Ruby and Rails-specific exclude patterns for better performance. """ base_patterns = [ "**/vendor/**", # Ruby vendor directory (similar to node_modules) "**/.bundle/**", # Bundler cache "**/tmp/**", # Temporary files "**/log/**", # Log files "**/coverage/**", # Test coverage reports "**/.yardoc/**", # YARD documentation cache "**/doc/**", # Generated documentation "**/.git/**", # Git directory "**/node_modules/**", # Node modules (for Rails with JS) "**/public/assets/**", # Rails compiled assets ]
# Add Rails-specific patterns if this is a Rails project if Solargraph._detect_rails_project(repository_root_path): rails_patterns = [ "**/public/packs/**", # Webpacker output "**/public/webpack/**", # Webpack output "**/storage/**", # Active Storage files "**/tmp/cache/**", # Rails cache "**/tmp/pids/**", # Process IDs "**/tmp/sessions/**", # Session files "**/tmp/sockets/**", # Socket files "**/db/*.sqlite3", # SQLite databases ] base_patterns.extend(rails_patterns)
return base_patterns
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Solargraph Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() exclude_patterns = Solargraph._get_ruby_exclude_patterns(repository_absolute_path)
initialize_params: InitializeParams = { # type: ignore "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "initializationOptions": { "exclude": exclude_patterns, }, "capabilities": { "workspace": { "workspaceEdit": {"documentChanges": True}, }, "textDocument": { "documentSymbol": { "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, }, }, "trace": "verbose", "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the Solargraph Language Server for Ruby """
def register_capability_handler(params): assert "registrations" in params for registration in params["registrations"]: if registration["method"] == "workspace/executeCommand": self.initialize_searcher_command_available.set() self.resolve_main_method_available.set() return
def lang_status_handler(params): self.logger.log(f"LSP: language/status: {params}", logging.INFO) if params.get("type") == "ServiceReady" and params.get("message") == "Service is ready.": self.logger.log("Solargraph service is ready.", logging.INFO) self.analysis_complete.set() self.completions_available.set()
def execute_client_command_handler(params): return []
def do_nothing(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("language/status", lang_status_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("language/actionableNotification", do_nothing)
self.logger.log("Starting solargraph server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) self.logger.log(f"Sending init params: {json.dumps(initialize_params, indent=4)}", logging.INFO) init_response = self.server.send.initialize(initialize_params) self.logger.log(f"Received init response: {init_response}", logging.INFO) assert init_response["capabilities"]["textDocumentSync"] == 2 assert "completionProvider" in init_response["capabilities"] assert init_response["capabilities"]["completionProvider"] == { "resolveProvider": True, "triggerCharacters": [".", ":", "@"], } self.server.notify.initialized({})
# Wait for Solargraph to complete its initial workspace analysis # This prevents issues by ensuring background tasks finish self.logger.log("Waiting for Solargraph to complete initial workspace analysis...", logging.INFO) if self.analysis_complete.wait(timeout=60.0): self.logger.log("Solargraph initial analysis complete, server ready", logging.INFO) else: self.logger.log("Timeout waiting for Solargraph analysis completion, proceeding anyway", logging.WARNING) # Fallback: assume analysis is complete after timeout self.analysis_complete.set() self.completions_available.set()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358import loggingimport osimport pathlibimport subprocessimport threadingimport time
from overrides import override
from solidlsp import ls_typesfrom solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class SourceKitLSP(SolidLanguageServer): """ Provides Swift specific instantiation of the LanguageServer class using sourcekit-lsp. """
@override def is_ignored_dirname(self, dirname: str) -> bool: # For Swift projects, we should ignore: # - .build: Swift Package Manager build artifacts # - .swiftpm: Swift Package Manager metadata # - node_modules: if the project has JavaScript components # - dist/build: common output directories return super().is_ignored_dirname(dirname) or dirname in [".build", ".swiftpm", "node_modules", "dist", "build"]
@staticmethod def _get_sourcekit_lsp_version() -> str: """Get the installed sourcekit-lsp version or raise error if sourcekit was not found.""" try: result = subprocess.run(["sourcekit-lsp", "-h"], capture_output=True, text=True, check=False) if result.returncode == 0: return result.stdout.strip() else: raise Exception(f"`sourcekit-lsp -h` resulted in: {result}") except Exception as e: raise RuntimeError( "Could not find sourcekit-lsp, please install it as described in https://github.com/apple/sourcekit-lsp#installation" "And make sure it is available on your PATH." ) from e
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): sourcekit_version = self._get_sourcekit_lsp_version() logger.log(f"Starting sourcekit lsp with version: {sourcekit_version}", logging.INFO)
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd="sourcekit-lsp", cwd=repository_root_path), "swift", solidlsp_settings, ) self.server_ready = threading.Event() self.request_id = 0 self._did_sleep_before_requesting_references = False
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Swift Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri()
initialize_params = { "capabilities": { "general": { "markdown": {"parser": "marked", "version": "1.1.0"}, "positionEncodings": ["utf-16"], "regularExpressions": {"engine": "ECMAScript", "version": "ES2020"}, "staleRequestSupport": { "cancel": True, "retryOnContentModified": [ "textDocument/semanticTokens/full", "textDocument/semanticTokens/range", "textDocument/semanticTokens/full/delta", ], }, }, "notebookDocument": {"synchronization": {"dynamicRegistration": True, "executionSummarySupport": True}}, "textDocument": { "callHierarchy": {"dynamicRegistration": True}, "codeAction": { "codeActionLiteralSupport": { "codeActionKind": { "valueSet": [ "", "quickfix", "refactor", "refactor.extract", "refactor.inline", "refactor.rewrite", "source", "source.organizeImports", ] } }, "dataSupport": True, "disabledSupport": True, "dynamicRegistration": True, "honorsChangeAnnotations": True, "isPreferredSupport": True, "resolveSupport": {"properties": ["edit"]}, }, "codeLens": {"dynamicRegistration": True}, "colorProvider": {"dynamicRegistration": True}, "completion": { "completionItem": { "commitCharactersSupport": True, "deprecatedSupport": True, "documentationFormat": ["markdown", "plaintext"], "insertReplaceSupport": True, "insertTextModeSupport": {"valueSet": [1, 2]}, "labelDetailsSupport": True, "preselectSupport": True, "resolveSupport": {"properties": ["documentation", "detail", "additionalTextEdits"]}, "snippetSupport": True, "tagSupport": {"valueSet": [1]}, }, "completionItemKind": { "valueSet": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] }, "completionList": {"itemDefaults": ["commitCharacters", "editRange", "insertTextFormat", "insertTextMode", "data"]}, "contextSupport": True, "dynamicRegistration": True, "insertTextMode": 2, }, "declaration": {"dynamicRegistration": True, "linkSupport": True}, "definition": {"dynamicRegistration": True, "linkSupport": True}, "diagnostic": {"dynamicRegistration": True, "relatedDocumentSupport": False}, "documentHighlight": {"dynamicRegistration": True}, "documentLink": {"dynamicRegistration": True, "tooltipSupport": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "labelSupport": True, "symbolKind": { "valueSet": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] }, "tagSupport": {"valueSet": [1]}, }, "foldingRange": { "dynamicRegistration": True, "foldingRange": {"collapsedText": False}, "foldingRangeKind": {"valueSet": ["comment", "imports", "region"]}, "lineFoldingOnly": True, "rangeLimit": 5000, }, "formatting": {"dynamicRegistration": True}, "hover": {"contentFormat": ["markdown", "plaintext"], "dynamicRegistration": True}, "implementation": {"dynamicRegistration": True, "linkSupport": True}, "inlayHint": { "dynamicRegistration": True, "resolveSupport": {"properties": ["tooltip", "textEdits", "label.tooltip", "label.location", "label.command"]}, }, "inlineValue": {"dynamicRegistration": True}, "linkedEditingRange": {"dynamicRegistration": True}, "onTypeFormatting": {"dynamicRegistration": True}, "publishDiagnostics": { "codeDescriptionSupport": True, "dataSupport": True, "relatedInformation": True, "tagSupport": {"valueSet": [1, 2]}, "versionSupport": False, }, "rangeFormatting": {"dynamicRegistration": True, "rangesSupport": True}, "references": {"dynamicRegistration": True}, "rename": { "dynamicRegistration": True, "honorsChangeAnnotations": True, "prepareSupport": True, "prepareSupportDefaultBehavior": 1, }, "selectionRange": {"dynamicRegistration": True}, "semanticTokens": { "augmentsSyntaxTokens": True, "dynamicRegistration": True, "formats": ["relative"], "multilineTokenSupport": False, "overlappingTokenSupport": False, "requests": {"full": {"delta": True}, "range": True}, "serverCancelSupport": True, "tokenModifiers": [ "declaration", "definition", "readonly", "static", "deprecated", "abstract", "async", "modification", "documentation", "defaultLibrary", ], "tokenTypes": [ "namespace", "type", "class", "enum", "interface", "struct", "typeParameter", "parameter", "variable", "property", "enumMember", "event", "function", "method", "macro", "keyword", "modifier", "comment", "string", "number", "regexp", "operator", "decorator", ], }, "signatureHelp": { "contextSupport": True, "dynamicRegistration": True, "signatureInformation": { "activeParameterSupport": True, "documentationFormat": ["markdown", "plaintext"], "parameterInformation": {"labelOffsetSupport": True}, }, }, "synchronization": {"didSave": True, "dynamicRegistration": True, "willSave": True, "willSaveWaitUntil": True}, "typeDefinition": {"dynamicRegistration": True, "linkSupport": True}, "typeHierarchy": {"dynamicRegistration": True}, }, "window": { "showDocument": {"support": True}, "showMessage": {"messageActionItem": {"additionalPropertiesSupport": True}}, "workDoneProgress": True, }, "workspace": { "applyEdit": True, "codeLens": {"refreshSupport": True}, "configuration": True, "diagnostics": {"refreshSupport": True}, "didChangeConfiguration": {"dynamicRegistration": True}, "didChangeWatchedFiles": {"dynamicRegistration": True, "relativePatternSupport": True}, "executeCommand": {"dynamicRegistration": True}, "fileOperations": { "didCreate": True, "didDelete": True, "didRename": True, "dynamicRegistration": True, "willCreate": True, "willDelete": True, "willRename": True, }, "foldingRange": {"refreshSupport": True}, "inlayHint": {"refreshSupport": True}, "inlineValue": {"refreshSupport": True}, "semanticTokens": {"refreshSupport": False}, "symbol": { "dynamicRegistration": True, "resolveSupport": {"properties": ["location.range"]}, "symbolKind": { "valueSet": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26] }, "tagSupport": {"valueSet": [1]}, }, "workspaceEdit": { "changeAnnotationSupport": {"groupsOnLabel": True}, "documentChanges": True, "failureHandling": "textOnlyTransactional", "normalizesLineEndings": True, "resourceOperations": ["create", "rename", "delete"], }, "workspaceFolders": True, }, }, "clientInfo": {"name": "Visual Studio Code", "version": "1.102.2"}, "initializationOptions": { "backgroundIndexing": True, "backgroundPreparationMode": "enabled", "textDocument/codeLens": {"supportedCommands": {"swift.debug": "swift.debug", "swift.run": "swift.run"}}, "window/didChangeActiveDocument": True, "workspace/getReferenceDocument": True, "workspace/peekDocuments": True, }, "locale": "en", "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], }
return initialize_params
def _start_server(self): """Start sourcekit-lsp server process"""
def register_capability_handler(_params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(_params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting sourcekit-lsp server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
capabilities = init_response["capabilities"] self.logger.log(f"SourceKit LSP capabilities: {list(capabilities.keys())}", logging.INFO)
assert "textDocumentSync" in capabilities, "textDocumentSync capability missing" assert "definitionProvider" in capabilities, "definitionProvider capability missing"
self.server.notify.initialized({}) self.completions_available.set()
self.server_ready.set() self.server_ready.wait()
@override def request_references(self, relative_file_path: str, line: int, column: int) -> list[ls_types.Location]: # SourceKit LSP needs a short initialization period after startup # before it can provide accurate reference information. This sleep # prevents race conditions where references might not be available yet. # Unfortunately, sourcekit doesn't send a signal when it's really ready if not self._did_sleep_before_requesting_references: self.logger.log("Sleeping 5s before requesting references for the first time", logging.DEBUG) time.sleep(5) self._did_sleep_before_requesting_references = True return super().request_references(relative_file_path, line, column)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214import loggingimport osimport shutilimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import PathUtils, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
from .common import RuntimeDependency, RuntimeDependencyCollection
class TerraformLS(SolidLanguageServer): """ Provides Terraform specific instantiation of the LanguageServer class using terraform-ls. """
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in [".terraform", "terraform.tfstate.d"]
@staticmethod def _ensure_tf_command_available(logger: LanguageServerLogger): logger.log("Starting terraform version detection...", logging.DEBUG)
# 1. Try to find terraform using shutil.which terraform_cmd = shutil.which("terraform") if terraform_cmd is not None: logger.log(f"Found terraform via shutil.which: {terraform_cmd}", logging.DEBUG) return
# TODO: is this needed? # 2. Fallback to TERRAFORM_CLI_PATH (set by hashicorp/setup-terraform action) if not terraform_cmd: terraform_cli_path = os.environ.get("TERRAFORM_CLI_PATH") if terraform_cli_path: logger.log(f"Trying TERRAFORM_CLI_PATH: {terraform_cli_path}", logging.DEBUG) # TODO: use binary name from runtime dependencies if we keep this code if os.name == "nt": terraform_binary = os.path.join(terraform_cli_path, "terraform.exe") else: terraform_binary = os.path.join(terraform_cli_path, "terraform") if os.path.exists(terraform_binary): terraform_cmd = terraform_binary logger.log(f"Found terraform via TERRAFORM_CLI_PATH: {terraform_cmd}", logging.DEBUG) return
raise RuntimeError( "Terraform executable not found, please ensure Terraform is installed." "See https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli for instructions." )
@classmethod def _setup_runtime_dependencies(cls, logger: LanguageServerLogger, solidlsp_settings: SolidLSPSettings) -> str: """ Setup runtime dependencies for terraform-ls. Downloads and installs terraform-ls if not already present. """ cls._ensure_tf_command_available(logger) platform_id = PlatformUtils.get_platform_id() deps = RuntimeDependencyCollection( [ RuntimeDependency( id="TerraformLS", description="terraform-ls for macOS (ARM64)", url="https://releases.hashicorp.com/terraform-ls/0.36.5/terraform-ls_0.36.5_darwin_arm64.zip", platform_id="osx-arm64", archive_type="zip", binary_name="terraform-ls", ), RuntimeDependency( id="TerraformLS", description="terraform-ls for macOS (x64)", url="https://releases.hashicorp.com/terraform-ls/0.36.5/terraform-ls_0.36.5_darwin_amd64.zip", platform_id="osx-x64", archive_type="zip", binary_name="terraform-ls", ), RuntimeDependency( id="TerraformLS", description="terraform-ls for Linux (ARM64)", url="https://releases.hashicorp.com/terraform-ls/0.36.5/terraform-ls_0.36.5_linux_arm64.zip", platform_id="linux-arm64", archive_type="zip", binary_name="terraform-ls", ), RuntimeDependency( id="TerraformLS", description="terraform-ls for Linux (x64)", url="https://releases.hashicorp.com/terraform-ls/0.36.5/terraform-ls_0.36.5_linux_amd64.zip", platform_id="linux-x64", archive_type="zip", binary_name="terraform-ls", ), RuntimeDependency( id="TerraformLS", description="terraform-ls for Windows (x64)", url="https://releases.hashicorp.com/terraform-ls/0.36.5/terraform-ls_0.36.5_windows_amd64.zip", platform_id="win-x64", archive_type="zip", binary_name="terraform-ls.exe", ), ] ) dependency = deps.single_for_current_platform()
terraform_ls_executable_path = deps.binary_path(cls.ls_resources_dir(solidlsp_settings)) if not os.path.exists(terraform_ls_executable_path): logger.log(f"Downloading terraform-ls from {dependency.url}", logging.INFO) deps.install(logger, cls.ls_resources_dir(solidlsp_settings))
assert os.path.exists(terraform_ls_executable_path), f"terraform-ls executable not found at {terraform_ls_executable_path}"
# Make the executable file executable on Unix-like systems if platform_id.value != "win-x64": os.chmod(terraform_ls_executable_path, 0o755)
return terraform_ls_executable_path
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a TerraformLS instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ terraform_ls_executable_path = self._setup_runtime_dependencies(logger, solidlsp_settings)
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=f"{terraform_ls_executable_path} serve", cwd=repository_root_path), "terraform", solidlsp_settings, ) self.server_ready = threading.Event() self.request_id = 0
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Terraform Language Server. """ root_uri = PathUtils.path_to_uri(repository_absolute_path) return { "processId": os.getpid(), "locale": "en", "rootPath": repository_absolute_path, "rootUri": root_uri, "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "completion": {"dynamicRegistration": True, "completionItem": {"snippetSupport": True}}, "definition": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, }, "workspace": {"workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}}, }, "workspaceFolders": [ { "name": os.path.basename(repository_absolute_path), "uri": root_uri, } ], }
def _start_server(self): """Start terraform-ls server process"""
def register_capability_handler(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting terraform-ls server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# Verify server capabilities assert "textDocumentSync" in init_response["capabilities"] assert "completionProvider" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"]
self.server.notify.initialized({}) self.completions_available.set()
# terraform-ls server is typically ready immediately after initialization self.server_ready.set() self.server_ready.wait()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253"""Provides TypeScript specific instantiation of the LanguageServer class. Contains various configurations and settings specific to TypeScript."""
import loggingimport osimport pathlibimport shutilimport threading
from overrides import overridefrom sensai.util.logging import LogTime
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import PlatformId, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
from .common import RuntimeDependency, RuntimeDependencyCollection
# Platform-specific importsif os.name != "nt": # Unix-like systems import pwdelse: # Dummy pwd module for Windows class pwd: @staticmethod def getpwuid(uid): return type("obj", (), {"pw_name": os.environ.get("USERNAME", "unknown")})()
# Conditionally import pwd module (Unix-only)if not PlatformUtils.get_platform_id().value.startswith("win"): pass
class TypeScriptLanguageServer(SolidLanguageServer): """ Provides TypeScript specific instantiation of the LanguageServer class. Contains various configurations and settings specific to TypeScript. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a TypeScriptLanguageServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ ts_lsp_executable_path = self._setup_runtime_dependencies(logger, config, solidlsp_settings) super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=ts_lsp_executable_path, cwd=repository_root_path), "typescript", solidlsp_settings, ) self.server_ready = threading.Event() self.initialize_searcher_command_available = threading.Event()
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in [ "node_modules", "dist", "build", "coverage", ]
@classmethod def _setup_runtime_dependencies( cls, logger: LanguageServerLogger, config: LanguageServerConfig, solidlsp_settings: SolidLSPSettings ) -> list[str]: """ Setup runtime dependencies for TypeScript Language Server and return the command to start the server. """ platform_id = PlatformUtils.get_platform_id()
valid_platforms = [ PlatformId.LINUX_x64, PlatformId.LINUX_arm64, PlatformId.OSX, PlatformId.OSX_x64, PlatformId.OSX_arm64, PlatformId.WIN_x64, PlatformId.WIN_arm64, ] assert platform_id in valid_platforms, f"Platform {platform_id} is not supported for multilspy javascript/typescript at the moment"
deps = RuntimeDependencyCollection( [ RuntimeDependency( id="typescript", description="typescript package", command=["npm", "install", "--prefix", "./", "typescript@5.5.4"], platform_id="any", ), RuntimeDependency( id="typescript-language-server", description="typescript-language-server package", command=["npm", "install", "--prefix", "./", "typescript-language-server@4.3.3"], platform_id="any", ), ] )
# Verify both node and npm are installed is_node_installed = shutil.which("node") is not None assert is_node_installed, "node is not installed or isn't in PATH. Please install NodeJS and try again." is_npm_installed = shutil.which("npm") is not None assert is_npm_installed, "npm is not installed or isn't in PATH. Please install npm and try again."
# Verify both node and npm are installed is_node_installed = shutil.which("node") is not None assert is_node_installed, "node is not installed or isn't in PATH. Please install NodeJS and try again." is_npm_installed = shutil.which("npm") is not None assert is_npm_installed, "npm is not installed or isn't in PATH. Please install npm and try again."
# Install typescript and typescript-language-server if not already installed tsserver_ls_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "ts-lsp") tsserver_executable_path = os.path.join(tsserver_ls_dir, "node_modules", ".bin", "typescript-language-server") if not os.path.exists(tsserver_executable_path): logger.log(f"Typescript Language Server executable not found at {tsserver_executable_path}. Installing...", logging.INFO) with LogTime("Installation of TypeScript language server dependencies", logger=logger.logger): deps.install(logger, tsserver_ls_dir)
if not os.path.exists(tsserver_executable_path): raise FileNotFoundError( f"typescript-language-server executable not found at {tsserver_executable_path}, something went wrong with the installation." ) return [tsserver_executable_path, "--stdio"]
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the TypeScript Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "completion": {"dynamicRegistration": True, "completionItem": {"snippetSupport": True}}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": {"dynamicRegistration": True}, "codeAction": {"dynamicRegistration": True}, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "symbol": {"dynamicRegistration": True}, }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the TypeScript Language Server, waits for the server to be ready and yields the LanguageServer instance.
Usage: ``` async with lsp.start_server(): # LanguageServer has been initialized and ready to serve requests await lsp.request_definition(...) await lsp.request_references(...) # Shutdown the LanguageServer on exit from scope # LanguageServer has been shutdown """
def register_capability_handler(params): assert "registrations" in params for registration in params["registrations"]: if registration["method"] == "workspace/executeCommand": self.initialize_searcher_command_available.set() # TypeScript doesn't have a direct equivalent to resolve_main_method # You might want to set a different flag or remove this line # self.resolve_main_method_available.set() return
def execute_client_command_handler(params): return []
def do_nothing(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def check_experimental_status(params): """ Also listen for experimental/serverStatus as a backup signal """ if params.get("quiescent") == True: self.server_ready.set() self.completions_available.set()
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status)
self.logger.log("Starting TypeScript server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# TypeScript-specific capability checks assert init_response["capabilities"]["textDocumentSync"] == 2 assert "completionProvider" in init_response["capabilities"] assert init_response["capabilities"]["completionProvider"] == { "triggerCharacters": [".", '"', "'", "/", "@", "<"], "resolveProvider": True, }
self.server.notify.initialized({}) if self.server_ready.wait(timeout=1.0): self.logger.log("TypeScript server is ready", logging.INFO) else: self.logger.log("Timeout waiting for TypeScript server to become ready, proceeding anyway", logging.INFO) # Fallback: assume server is ready after timeout self.server_ready.set() self.completions_available.set()
@override def _get_wait_time_for_cross_file_referencing(self) -> float: return 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235"""Language Server implementation for TypeScript/JavaScript using https://github.com/yioneko/vtsls,which provides TypeScript language server functionality via VSCode's TypeScript extension(contrary to typescript-language-server, which uses the TypeScript compiler directly)."""
import loggingimport osimport pathlibimport shutilimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.ls_utils import PlatformId, PlatformUtilsfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
from .common import RuntimeDependency, RuntimeDependencyCollection
class VtsLanguageServer(SolidLanguageServer): """ Provides TypeScript specific instantiation of the LanguageServer class using vtsls. Contains various configurations and settings specific to TypeScript via vtsls wrapper. """
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): """ Creates a VtsLanguageServer instance. This class is not meant to be instantiated directly. Use LanguageServer.create() instead. """ vts_lsp_executable_path = self._setup_runtime_dependencies(logger, config, solidlsp_settings) super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd=vts_lsp_executable_path, cwd=repository_root_path), "typescript", solidlsp_settings, ) self.server_ready = threading.Event() self.initialize_searcher_command_available = threading.Event()
@override def is_ignored_dirname(self, dirname: str) -> bool: return super().is_ignored_dirname(dirname) or dirname in [ "node_modules", "dist", "build", "coverage", ]
@classmethod def _setup_runtime_dependencies( cls, logger: LanguageServerLogger, config: LanguageServerConfig, solidlsp_settings: SolidLSPSettings ) -> str: """ Setup runtime dependencies for VTS Language Server and return the command to start the server. """ platform_id = PlatformUtils.get_platform_id()
valid_platforms = [ PlatformId.LINUX_x64, PlatformId.LINUX_arm64, PlatformId.OSX, PlatformId.OSX_x64, PlatformId.OSX_arm64, PlatformId.WIN_x64, PlatformId.WIN_arm64, ] assert platform_id in valid_platforms, f"Platform {platform_id} is not supported for vtsls at the moment"
deps = RuntimeDependencyCollection( [ RuntimeDependency( id="vtsls", description="vtsls language server package", command="npm install --prefix ./ @vtsls/language-server@0.2.9", platform_id="any", ), ] ) vts_ls_dir = os.path.join(cls.ls_resources_dir(solidlsp_settings), "vts-lsp") vts_executable_path = os.path.join(vts_ls_dir, "vtsls")
# Verify both node and npm are installed is_node_installed = shutil.which("node") is not None assert is_node_installed, "node is not installed or isn't in PATH. Please install NodeJS and try again." is_npm_installed = shutil.which("npm") is not None assert is_npm_installed, "npm is not installed or isn't in PATH. Please install npm and try again."
# Install vtsls if not already installed if not os.path.exists(vts_ls_dir): os.makedirs(vts_ls_dir, exist_ok=True) deps.install(logger, vts_ls_dir)
vts_executable_path = os.path.join(vts_ls_dir, "node_modules", ".bin", "vtsls")
assert os.path.exists(vts_executable_path), "vtsls executable not found. Please install @vtsls/language-server and try again." return f"{vts_executable_path} --stdio"
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the VTS Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "hover": {"dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"]}, "signatureHelp": {"dynamicRegistration": True}, "codeAction": {"dynamicRegistration": True}, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "symbol": {"dynamicRegistration": True}, "configuration": True, # This might be needed for vtsls }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], } return initialize_params
def _start_server(self): """ Starts the VTS Language Server, waits for the server to be ready and yields the LanguageServer instance.
Usage: ``` async with lsp.start_server(): # LanguageServer has been initialized and ready to serve requests await lsp.request_definition(...) await lsp.request_references(...) # Shutdown the LanguageServer on exit from scope # LanguageServer has been shutdown """
def register_capability_handler(params): assert "registrations" in params for registration in params["registrations"]: if registration["method"] == "workspace/executeCommand": self.initialize_searcher_command_available.set() return
def execute_client_command_handler(params): return []
def workspace_configuration_handler(params): # VTS may request workspace configuration # Return empty configuration for each requested item if "items" in params: return [{}] * len(params["items"]) return {}
def do_nothing(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def check_experimental_status(params): """ Also listen for experimental/serverStatus as a backup signal """ if params.get("quiescent") is True: self.server_ready.set() self.completions_available.set()
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_request("workspace/executeClientCommand", execute_client_command_handler) self.server.on_request("workspace/configuration", workspace_configuration_handler) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing) self.server.on_notification("experimental/serverStatus", check_experimental_status)
self.logger.log("Starting VTS server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# VTS-specific capability checks # Be more flexible with capabilities since vtsls might have different structure self.logger.log(f"VTS init response capabilities: {init_response['capabilities']}", logging.DEBUG)
# Basic checks to ensure essential capabilities are present assert "textDocumentSync" in init_response["capabilities"] assert "completionProvider" in init_response["capabilities"]
# Log the actual values for debugging self.logger.log(f"textDocumentSync: {init_response['capabilities']['textDocumentSync']}", logging.DEBUG) self.logger.log(f"completionProvider: {init_response['capabilities']['completionProvider']}", logging.DEBUG)
self.server.notify.initialized({}) if self.server_ready.wait(timeout=1.0): self.logger.log("VTS server is ready", logging.INFO) else: self.logger.log("Timeout waiting for VTS server to become ready, proceeding anyway", logging.INFO) # Fallback: assume server is ready after timeout self.server_ready.set() self.completions_available.set()
@override def _get_wait_time_for_cross_file_referencing(self) -> float: return 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""Provides Zig specific instantiation of the LanguageServer class using ZLS (Zig Language Server)."""
import loggingimport osimport pathlibimport platformimport shutilimport subprocessimport threading
from overrides import override
from solidlsp.ls import SolidLanguageServerfrom solidlsp.ls_config import LanguageServerConfigfrom solidlsp.ls_logger import LanguageServerLoggerfrom solidlsp.lsp_protocol_handler.lsp_types import InitializeParamsfrom solidlsp.lsp_protocol_handler.server import ProcessLaunchInfofrom solidlsp.settings import SolidLSPSettings
class ZigLanguageServer(SolidLanguageServer): """ Provides Zig specific instantiation of the LanguageServer class using ZLS. """
@override def is_ignored_dirname(self, dirname: str) -> bool: # For Zig projects, we should ignore: # - zig-cache: build cache directory # - zig-out: default build output directory # - .zig-cache: alternative cache location # - node_modules: if the project has JavaScript components return super().is_ignored_dirname(dirname) or dirname in ["zig-cache", "zig-out", ".zig-cache", "node_modules", "build", "dist"]
@staticmethod def _get_zig_version(): """Get the installed Zig version or None if not found.""" try: result = subprocess.run(["zig", "version"], capture_output=True, text=True, check=False) if result.returncode == 0: return result.stdout.strip() except FileNotFoundError: return None return None
@staticmethod def _get_zls_version(): """Get the installed ZLS version or None if not found.""" try: result = subprocess.run(["zls", "--version"], capture_output=True, text=True, check=False) if result.returncode == 0: return result.stdout.strip() except FileNotFoundError: return None return None
@staticmethod def _check_zls_installed(): """Check if ZLS is installed in the system.""" return shutil.which("zls") is not None
@staticmethod def _setup_runtime_dependency(): """ Check if required Zig runtime dependencies are available. Raises RuntimeError with helpful message if dependencies are missing. """ # Check for Windows and provide error message if platform.system() == "Windows": raise RuntimeError( "Windows is not supported by ZLS in this integration. " "Cross-file references don't work reliably on Windows. Reason unknown." )
zig_version = ZigLanguageServer._get_zig_version() if not zig_version: raise RuntimeError( "Zig is not installed. Please install Zig from https://ziglang.org/download/ and make sure it is added to your PATH." )
if not ZigLanguageServer._check_zls_installed(): zls_version = ZigLanguageServer._get_zls_version() if not zls_version: raise RuntimeError( "Found Zig but ZLS (Zig Language Server) is not installed.\n" "Please install ZLS from https://github.com/zigtools/zls\n" "You can install it via:\n" " - Package managers (brew install zls, scoop install zls, etc.)\n" " - Download pre-built binaries from GitHub releases\n" " - Build from source with: zig build -Doptimize=ReleaseSafe\n\n" "After installation, make sure 'zls' is added to your PATH." )
return True
def __init__( self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str, solidlsp_settings: SolidLSPSettings ): self._setup_runtime_dependency()
super().__init__( config, logger, repository_root_path, ProcessLaunchInfo(cmd="zls", cwd=repository_root_path), "zig", solidlsp_settings, ) self.server_ready = threading.Event() self.request_id = 0
@staticmethod def _get_initialize_params(repository_absolute_path: str) -> InitializeParams: """ Returns the initialize params for the Zig Language Server. """ root_uri = pathlib.Path(repository_absolute_path).as_uri() initialize_params = { "locale": "en", "capabilities": { "textDocument": { "synchronization": {"didSave": True, "dynamicRegistration": True}, "definition": {"dynamicRegistration": True}, "references": {"dynamicRegistration": True}, "documentSymbol": { "dynamicRegistration": True, "hierarchicalDocumentSymbolSupport": True, "symbolKind": {"valueSet": list(range(1, 27))}, }, "completion": { "dynamicRegistration": True, "completionItem": { "snippetSupport": True, "commitCharactersSupport": True, "documentationFormat": ["markdown", "plaintext"], "deprecatedSupport": True, "preselectSupport": True, }, }, "hover": { "dynamicRegistration": True, "contentFormat": ["markdown", "plaintext"], }, }, "workspace": { "workspaceFolders": True, "didChangeConfiguration": {"dynamicRegistration": True}, "configuration": True, }, }, "processId": os.getpid(), "rootPath": repository_absolute_path, "rootUri": root_uri, "workspaceFolders": [ { "uri": root_uri, "name": os.path.basename(repository_absolute_path), } ], "initializationOptions": { # ZLS specific options based on schema.json # Critical paths for ZLS to understand the project "zig_exe_path": shutil.which("zig"), # Path to zig executable "zig_lib_path": None, # Let ZLS auto-detect "build_runner_path": None, # Let ZLS use its built-in runner "global_cache_path": None, # Let ZLS use default cache # Build configuration "enable_build_on_save": True, # Enable to analyze project structure "build_on_save_args": ["build"], # Features "enable_snippets": True, "enable_argument_placeholders": True, "semantic_tokens": "full", "warn_style": False, "highlight_global_var_declarations": False, "skip_std_references": False, "prefer_ast_check_as_child_process": True, "completion_label_details": True, # Inlay hints configuration "inlay_hints_show_variable_type_hints": True, "inlay_hints_show_struct_literal_field_type": True, "inlay_hints_show_parameter_name": True, "inlay_hints_show_builtin": True, "inlay_hints_exclude_single_argument": True, "inlay_hints_hide_redundant_param_names": False, "inlay_hints_hide_redundant_param_names_last_token": False, }, } return initialize_params
def _start_server(self): """Start ZLS server process"""
def register_capability_handler(params): return
def window_log_message(msg): self.logger.log(f"LSP: window/logMessage: {msg}", logging.INFO)
def do_nothing(params): return
self.server.on_request("client/registerCapability", register_capability_handler) self.server.on_notification("window/logMessage", window_log_message) self.server.on_notification("$/progress", do_nothing) self.server.on_notification("textDocument/publishDiagnostics", do_nothing)
self.logger.log("Starting ZLS server process", logging.INFO) self.server.start() initialize_params = self._get_initialize_params(self.repository_root_path)
self.logger.log( "Sending initialize request from LSP client to LSP server and awaiting response", logging.INFO, ) init_response = self.server.send.initialize(initialize_params)
# Verify server capabilities assert "textDocumentSync" in init_response["capabilities"] assert "definitionProvider" in init_response["capabilities"] assert "documentSymbolProvider" in init_response["capabilities"] assert "referencesProvider" in init_response["capabilities"]
self.server.notify.initialized({}) self.completions_available.set()
# ZLS server is ready after initialization self.server_ready.set() self.server_ready.wait()
# Open build.zig if it exists to help ZLS understand project structure build_zig_path = os.path.join(self.repository_root_path, "build.zig") if os.path.exists(build_zig_path): try: with open(build_zig_path, encoding="utf-8") as f: content = f.read() uri = pathlib.Path(build_zig_path).as_uri() self.server.notify.did_open_text_document( { "textDocument": { "uri": uri, "languageId": "zig", "version": 1, "text": content, } } ) self.logger.log("Opened build.zig to provide project context to ZLS", logging.INFO) except Exception as e: self.logger.log(f"Failed to open build.zig: {e}", logging.WARNING)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""This module contains constants used in the LSP protocol."""
class LSPConstants: """ This class contains constants used in the LSP protocol. """
# the key for uri used to represent paths URI = "uri"
# the key for range, which is a from and to position within a text document RANGE = "range"
# A key used in LocationLink type, used as the span of the origin link ORIGIN_SELECTION_RANGE = "originSelectionRange"
# A key used in LocationLink type, used as the target uri of the link TARGET_URI = "targetUri"
# A key used in LocationLink type, used as the target range of the link TARGET_RANGE = "targetRange"
# A key used in LocationLink type, used as the target selection range of the link TARGET_SELECTION_RANGE = "targetSelectionRange"
# key for the textDocument field in the request TEXT_DOCUMENT = "textDocument"
# key used to represent the language a document is in - "java", "csharp", etc. LANGUAGE_ID = "languageId"
# key used to represent the version of a document (a shared value between the client and server) VERSION = "version"
# key used to represent the text of a document being sent from the client to the server on open TEXT = "text"
# key used to represent a position (line and colnum) within a text document POSITION = "position"
# key used to represent the line number of a position LINE = "line"
# key used to represent the column number of a position CHARACTER = "character"
# key used to represent the changes made to a document CONTENT_CHANGES = "contentChanges"
# key used to represent name of symbols NAME = "name"
# key used to represent the kind of symbols KIND = "kind"
# key used to represent children in document symbols CHILDREN = "children"
# key used to represent the location in symbols LOCATION = "location"
# Severity level of the diagnostic SEVERITY = "severity"
# The message of the diagnostic MESSAGE = "message"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561# Code generated. DO NOT EDIT.# LSP v3.17.0# TODO: Look into use of https://pypi.org/project/ts2python/ to generate the types for https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/
"""This file provides the python interface corresponding to the requests and notifications defined in Typescript in the language server protocol.This file is obtained from https://github.com/predragnikolic/OLSP under the MIT License with the following terms:
MIT License
Copyright (c) 2023 Предраг Николић
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE."""
from typing import Union
from solidlsp.lsp_protocol_handler import lsp_types
class LspRequest: def __init__(self, send_request): self.send_request = send_request
async def implementation( self, params: lsp_types.ImplementationParams ) -> Union["lsp_types.Definition", list["lsp_types.LocationLink"], None]: """A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type [TextDocumentPositionParams] (#TextDocumentPositionParams) the response is of type {@link Definition} or a Thenable that resolves to such. """ return await self.send_request("textDocument/implementation", params)
async def type_definition( self, params: lsp_types.TypeDefinitionParams ) -> Union["lsp_types.Definition", list["lsp_types.LocationLink"], None]: """A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type [TextDocumentPositionParams] (#TextDocumentPositionParams) the response is of type {@link Definition} or a Thenable that resolves to such. """ return await self.send_request("textDocument/typeDefinition", params)
async def document_color(self, params: lsp_types.DocumentColorParams) -> list["lsp_types.ColorInformation"]: """A request to list all color symbols found in a given text document. The request's parameter is of type {@link DocumentColorParams} the response is of type {@link ColorInformation ColorInformation[]} or a Thenable that resolves to such. """ return await self.send_request("textDocument/documentColor", params)
async def color_presentation(self, params: lsp_types.ColorPresentationParams) -> list["lsp_types.ColorPresentation"]: """A request to list all presentation for a color. The request's parameter is of type {@link ColorPresentationParams} the response is of type {@link ColorInformation ColorInformation[]} or a Thenable that resolves to such. """ return await self.send_request("textDocument/colorPresentation", params)
async def folding_range(self, params: lsp_types.FoldingRangeParams) -> list["lsp_types.FoldingRange"] | None: """A request to provide folding ranges in a document. The request's parameter is of type {@link FoldingRangeParams}, the response is of type {@link FoldingRangeList} or a Thenable that resolves to such. """ return await self.send_request("textDocument/foldingRange", params)
async def declaration( self, params: lsp_types.DeclarationParams ) -> Union["lsp_types.Declaration", list["lsp_types.LocationLink"], None]: """A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type [TextDocumentPositionParams] (#TextDocumentPositionParams) the response is of type {@link Declaration} or a typed array of {@link DeclarationLink} or a Thenable that resolves to such. """ return await self.send_request("textDocument/declaration", params)
async def selection_range(self, params: lsp_types.SelectionRangeParams) -> list["lsp_types.SelectionRange"] | None: """A request to provide selection ranges in a document. The request's parameter is of type {@link SelectionRangeParams}, the response is of type {@link SelectionRange SelectionRange[]} or a Thenable that resolves to such. """ return await self.send_request("textDocument/selectionRange", params)
async def prepare_call_hierarchy(self, params: lsp_types.CallHierarchyPrepareParams) -> list["lsp_types.CallHierarchyItem"] | None: """A request to result a `CallHierarchyItem` in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy.
@since 3.16.0 """ return await self.send_request("textDocument/prepareCallHierarchy", params)
async def incoming_calls( self, params: lsp_types.CallHierarchyIncomingCallsParams ) -> list["lsp_types.CallHierarchyIncomingCall"] | None: """A request to resolve the incoming calls for a given `CallHierarchyItem`.
@since 3.16.0 """ return await self.send_request("callHierarchy/incomingCalls", params)
async def outgoing_calls( self, params: lsp_types.CallHierarchyOutgoingCallsParams ) -> list["lsp_types.CallHierarchyOutgoingCall"] | None: """A request to resolve the outgoing calls for a given `CallHierarchyItem`.
@since 3.16.0 """ return await self.send_request("callHierarchy/outgoingCalls", params)
async def semantic_tokens_full(self, params: lsp_types.SemanticTokensParams) -> Union["lsp_types.SemanticTokens", None]: """@since 3.16.0""" return await self.send_request("textDocument/semanticTokens/full", params)
async def semantic_tokens_delta( self, params: lsp_types.SemanticTokensDeltaParams ) -> Union["lsp_types.SemanticTokens", "lsp_types.SemanticTokensDelta", None]: """@since 3.16.0""" return await self.send_request("textDocument/semanticTokens/full/delta", params)
async def semantic_tokens_range(self, params: lsp_types.SemanticTokensRangeParams) -> Union["lsp_types.SemanticTokens", None]: """@since 3.16.0""" return await self.send_request("textDocument/semanticTokens/range", params)
async def linked_editing_range(self, params: lsp_types.LinkedEditingRangeParams) -> Union["lsp_types.LinkedEditingRanges", None]: """A request to provide ranges that can be edited together.
@since 3.16.0 """ return await self.send_request("textDocument/linkedEditingRange", params)
async def will_create_files(self, params: lsp_types.CreateFilesParams) -> Union["lsp_types.WorkspaceEdit", None]: """The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client.
@since 3.16.0 """ return await self.send_request("workspace/willCreateFiles", params)
async def will_rename_files(self, params: lsp_types.RenameFilesParams) -> Union["lsp_types.WorkspaceEdit", None]: """The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client.
@since 3.16.0 """ return await self.send_request("workspace/willRenameFiles", params)
async def will_delete_files(self, params: lsp_types.DeleteFilesParams) -> Union["lsp_types.WorkspaceEdit", None]: """The did delete files notification is sent from the client to the server when files were deleted from within the client.
@since 3.16.0 """ return await self.send_request("workspace/willDeleteFiles", params)
async def moniker(self, params: lsp_types.MonikerParams) -> list["lsp_types.Moniker"] | None: """A request to get the moniker of a symbol at a given text document position. The request parameter is of type {@link TextDocumentPositionParams}. The response is of type {@link Moniker Moniker[]} or `null`. """ return await self.send_request("textDocument/moniker", params)
async def prepare_type_hierarchy(self, params: lsp_types.TypeHierarchyPrepareParams) -> list["lsp_types.TypeHierarchyItem"] | None: """A request to result a `TypeHierarchyItem` in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy.
@since 3.17.0 """ return await self.send_request("textDocument/prepareTypeHierarchy", params)
async def type_hierarchy_supertypes( self, params: lsp_types.TypeHierarchySupertypesParams ) -> list["lsp_types.TypeHierarchyItem"] | None: """A request to resolve the supertypes for a given `TypeHierarchyItem`.
@since 3.17.0 """ return await self.send_request("typeHierarchy/supertypes", params)
async def type_hierarchy_subtypes(self, params: lsp_types.TypeHierarchySubtypesParams) -> list["lsp_types.TypeHierarchyItem"] | None: """A request to resolve the subtypes for a given `TypeHierarchyItem`.
@since 3.17.0 """ return await self.send_request("typeHierarchy/subtypes", params)
async def inline_value(self, params: lsp_types.InlineValueParams) -> list["lsp_types.InlineValue"] | None: """A request to provide inline values in a document. The request's parameter is of type {@link InlineValueParams}, the response is of type {@link InlineValue InlineValue[]} or a Thenable that resolves to such.
@since 3.17.0 """ return await self.send_request("textDocument/inlineValue", params)
async def inlay_hint(self, params: lsp_types.InlayHintParams) -> list["lsp_types.InlayHint"] | None: """A request to provide inlay hints in a document. The request's parameter is of type {@link InlayHintsParams}, the response is of type {@link InlayHint InlayHint[]} or a Thenable that resolves to such.
@since 3.17.0 """ return await self.send_request("textDocument/inlayHint", params)
async def resolve_inlay_hint(self, params: lsp_types.InlayHint) -> "lsp_types.InlayHint": """A request to resolve additional properties for an inlay hint. The request's parameter is of type {@link InlayHint}, the response is of type {@link InlayHint} or a Thenable that resolves to such.
@since 3.17.0 """ return await self.send_request("inlayHint/resolve", params)
async def text_document_diagnostic(self, params: lsp_types.DocumentDiagnosticParams) -> "lsp_types.DocumentDiagnosticReport": """The document diagnostic request definition.
@since 3.17.0 """ return await self.send_request("textDocument/diagnostic", params)
async def workspace_diagnostic(self, params: lsp_types.WorkspaceDiagnosticParams) -> "lsp_types.WorkspaceDiagnosticReport": """The workspace diagnostic request definition.
@since 3.17.0 """ return await self.send_request("workspace/diagnostic", params)
async def initialize(self, params: lsp_types.InitializeParams) -> "lsp_types.InitializeResult": """The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type {@link InitializeParams} the response if of type {@link InitializeResult} of a Thenable that resolves to such. """ return await self.send_request("initialize", params)
async def shutdown(self) -> None: """A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event. """ return await self.send_request("shutdown")
async def will_save_wait_until(self, params: lsp_types.WillSaveTextDocumentParams) -> list["lsp_types.TextEdit"] | None: """A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable. """ return await self.send_request("textDocument/willSaveWaitUntil", params)
async def completion( self, params: lsp_types.CompletionParams ) -> Union[list["lsp_types.CompletionItem"], "lsp_types.CompletionList", None]: """Request to request completion at a given text document position. The request's parameter is of type {@link TextDocumentPosition} the response is of type {@link CompletionItem CompletionItem[]} or {@link CompletionList} or a Thenable that resolves to such.
The request can delay the computation of the {@link CompletionItem.detail `detail`} and {@link CompletionItem.documentation `documentation`} properties to the `completionItem/resolve` request. However, properties that are needed for the initial sorting and filtering, like `sortText`, `filterText`, `insertText`, and `textEdit`, must not be changed during resolve. """ return await self.send_request("textDocument/completion", params)
async def resolve_completion_item(self, params: lsp_types.CompletionItem) -> "lsp_types.CompletionItem": """Request to resolve additional information for a given completion item.The request's parameter is of type {@link CompletionItem} the response is of type {@link CompletionItem} or a Thenable that resolves to such. """ return await self.send_request("completionItem/resolve", params)
async def hover(self, params: lsp_types.HoverParams) -> Union["lsp_types.Hover", None]: """Request to request hover information at a given text document position. The request's parameter is of type {@link TextDocumentPosition} the response is of type {@link Hover} or a Thenable that resolves to such. """ return await self.send_request("textDocument/hover", params)
async def signature_help(self, params: lsp_types.SignatureHelpParams) -> Union["lsp_types.SignatureHelp", None]: return await self.send_request("textDocument/signatureHelp", params)
async def definition(self, params: lsp_types.DefinitionParams) -> Union["lsp_types.Definition", list["lsp_types.LocationLink"], None]: """A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type [TextDocumentPosition] (#TextDocumentPosition) the response is of either type {@link Definition} or a typed array of {@link DefinitionLink} or a Thenable that resolves to such. """ return await self.send_request("textDocument/definition", params)
async def references(self, params: lsp_types.ReferenceParams) -> list["lsp_types.Location"] | None: """A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type {@link ReferenceParams} the response is of type {@link Location Location[]} or a Thenable that resolves to such. """ return await self.send_request("textDocument/references", params)
async def document_highlight(self, params: lsp_types.DocumentHighlightParams) -> list["lsp_types.DocumentHighlight"] | None: """Request to resolve a {@link DocumentHighlight} for a given text document position. The request's parameter is of type [TextDocumentPosition] (#TextDocumentPosition) the request response is of type [DocumentHighlight[]] (#DocumentHighlight) or a Thenable that resolves to such. """ return await self.send_request("textDocument/documentHighlight", params)
async def document_symbol( self, params: lsp_types.DocumentSymbolParams ) -> list["lsp_types.SymbolInformation"] | list["lsp_types.DocumentSymbol"] | None: """A request to list all symbols found in a given text document. The request's parameter is of type {@link TextDocumentIdentifier} the response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable that resolves to such. """ return await self.send_request("textDocument/documentSymbol", params)
async def code_action(self, params: lsp_types.CodeActionParams) -> list[Union["lsp_types.Command", "lsp_types.CodeAction"]] | None: """A request to provide commands for the given text document and range.""" return await self.send_request("textDocument/codeAction", params)
async def resolve_code_action(self, params: lsp_types.CodeAction) -> "lsp_types.CodeAction": """Request to resolve additional information for a given code action.The request's parameter is of type {@link CodeAction} the response is of type {@link CodeAction} or a Thenable that resolves to such. """ return await self.send_request("codeAction/resolve", params)
async def workspace_symbol( self, params: lsp_types.WorkspaceSymbolParams ) -> list["lsp_types.SymbolInformation"] | list["lsp_types.WorkspaceSymbol"] | None: """A request to list project-wide symbols matching the query string given by the {@link WorkspaceSymbolParams}. The response is of type {@link SymbolInformation SymbolInformation[]} or a Thenable that resolves to such.
@since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability `workspace.symbol.resolveSupport`. """ return await self.send_request("workspace/symbol", params)
async def resolve_workspace_symbol(self, params: lsp_types.WorkspaceSymbol) -> "lsp_types.WorkspaceSymbol": """A request to resolve the range inside the workspace symbol's location.
@since 3.17.0 """ return await self.send_request("workspaceSymbol/resolve", params)
async def code_lens(self, params: lsp_types.CodeLensParams) -> list["lsp_types.CodeLens"] | None: """A request to provide code lens for the given text document.""" return await self.send_request("textDocument/codeLens", params)
async def resolve_code_lens(self, params: lsp_types.CodeLens) -> "lsp_types.CodeLens": """A request to resolve a command for a given code lens.""" return await self.send_request("codeLens/resolve", params)
async def document_link(self, params: lsp_types.DocumentLinkParams) -> list["lsp_types.DocumentLink"] | None: """A request to provide document links""" return await self.send_request("textDocument/documentLink", params)
async def resolve_document_link(self, params: lsp_types.DocumentLink) -> "lsp_types.DocumentLink": """Request to resolve additional information for a given document link. The request's parameter is of type {@link DocumentLink} the response is of type {@link DocumentLink} or a Thenable that resolves to such. """ return await self.send_request("documentLink/resolve", params)
async def formatting(self, params: lsp_types.DocumentFormattingParams) -> list["lsp_types.TextEdit"] | None: """A request to to format a whole document.""" return await self.send_request("textDocument/formatting", params)
async def range_formatting(self, params: lsp_types.DocumentRangeFormattingParams) -> list["lsp_types.TextEdit"] | None: """A request to to format a range in a document.""" return await self.send_request("textDocument/rangeFormatting", params)
async def on_type_formatting(self, params: lsp_types.DocumentOnTypeFormattingParams) -> list["lsp_types.TextEdit"] | None: """A request to format a document on type.""" return await self.send_request("textDocument/onTypeFormatting", params)
async def rename(self, params: lsp_types.RenameParams) -> Union["lsp_types.WorkspaceEdit", None]: """A request to rename a symbol.""" return await self.send_request("textDocument/rename", params)
async def prepare_rename(self, params: lsp_types.PrepareRenameParams) -> Union["lsp_types.PrepareRenameResult", None]: """A request to test and perform the setup necessary for a rename.
@since 3.16 - support for default behavior """ return await self.send_request("textDocument/prepareRename", params)
async def execute_command(self, params: lsp_types.ExecuteCommandParams) -> Union["lsp_types.LSPAny", None]: """A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace. """ return await self.send_request("workspace/executeCommand", params)
class LspNotification: def __init__(self, send_notification): self.send_notification = send_notification
def did_change_workspace_folders(self, params: lsp_types.DidChangeWorkspaceFoldersParams) -> None: """The `workspace/didChangeWorkspaceFolders` notification is sent from the client to the server when the workspace folder configuration changes. """ return self.send_notification("workspace/didChangeWorkspaceFolders", params)
def cancel_work_done_progress(self, params: lsp_types.WorkDoneProgressCancelParams) -> None: """The `window/workDoneProgress/cancel` notification is sent from the client to the server to cancel a progress initiated on the server side. """ return self.send_notification("window/workDoneProgress/cancel", params)
def did_create_files(self, params: lsp_types.CreateFilesParams) -> None: """The did create files notification is sent from the client to the server when files were created from within the client.
@since 3.16.0 """ return self.send_notification("workspace/didCreateFiles", params)
def did_rename_files(self, params: lsp_types.RenameFilesParams) -> None: """The did rename files notification is sent from the client to the server when files were renamed from within the client.
@since 3.16.0 """ return self.send_notification("workspace/didRenameFiles", params)
def did_delete_files(self, params: lsp_types.DeleteFilesParams) -> None: """The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client.
@since 3.16.0 """ return self.send_notification("workspace/didDeleteFiles", params)
def did_open_notebook_document(self, params: lsp_types.DidOpenNotebookDocumentParams) -> None: """A notification sent when a notebook opens.
@since 3.17.0 """ return self.send_notification("notebookDocument/didOpen", params)
def did_change_notebook_document(self, params: lsp_types.DidChangeNotebookDocumentParams) -> None: return self.send_notification("notebookDocument/didChange", params)
def did_save_notebook_document(self, params: lsp_types.DidSaveNotebookDocumentParams) -> None: """A notification sent when a notebook document is saved.
@since 3.17.0 """ return self.send_notification("notebookDocument/didSave", params)
def did_close_notebook_document(self, params: lsp_types.DidCloseNotebookDocumentParams) -> None: """A notification sent when a notebook closes.
@since 3.17.0 """ return self.send_notification("notebookDocument/didClose", params)
def initialized(self, params: lsp_types.InitializedParams) -> None: """The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client. """ return self.send_notification("initialized", params)
def exit(self) -> None: """The exit event is sent from the client to the server to ask the server to exit its process. """ return self.send_notification("exit")
def workspace_did_change_configuration(self, params: lsp_types.DidChangeConfigurationParams) -> None: """The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client. """ return self.send_notification("workspace/didChangeConfiguration", params)
def did_open_text_document(self, params: lsp_types.DidOpenTextDocumentParams) -> None: """The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one. """ return self.send_notification("textDocument/didOpen", params)
def did_change_text_document(self, params: lsp_types.DidChangeTextDocumentParams) -> None: """The document change notification is sent from the client to the server to signal changes to a text document. """ return self.send_notification("textDocument/didChange", params)
def did_close_text_document(self, params: lsp_types.DidCloseTextDocumentParams) -> None: """The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent. """ return self.send_notification("textDocument/didClose", params)
def did_save_text_document(self, params: lsp_types.DidSaveTextDocumentParams) -> None: """The document save notification is sent from the client to the server when the document got saved in the client. """ return self.send_notification("textDocument/didSave", params)
def will_save_text_document(self, params: lsp_types.WillSaveTextDocumentParams) -> None: """A document will save notification is sent from the client to the server before the document is actually saved. """ return self.send_notification("textDocument/willSave", params)
def did_change_watched_files(self, params: lsp_types.DidChangeWatchedFilesParams) -> None: """The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client. """ return self.send_notification("workspace/didChangeWatchedFiles", params)
def set_trace(self, params: lsp_types.SetTraceParams) -> None: return self.send_notification("$/setTrace", params)
def cancel_request(self, params: lsp_types.CancelParams) -> None: return self.send_notification("$/cancelRequest", params)
def progress(self, params: lsp_types.ProgressParams) -> None: return self.send_notification("$/progress", params)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""This file provides the implementation of the JSON-RPC client, that launches andcommunicates with the language server.
The initial implementation of this file was obtained fromhttps://github.com/predragnikolic/OLSP under the MIT License with the following terms:
MIT License
Copyright (c) 2023 Предраг Николић
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE."""
import dataclassesimport jsonimport loggingimport osfrom typing import Any, Union
from .lsp_types import ErrorCodes
StringDict = dict[str, Any]PayloadLike = Union[list[StringDict], StringDict, None]CONTENT_LENGTH = "Content-Length: "ENCODING = "utf-8"log = logging.getLogger(__name__)
@dataclasses.dataclassclass ProcessLaunchInfo: """ This class is used to store the information required to launch a process. """
# The command to launch the process cmd: str | list[str]
# The environment variables to set for the process env: dict[str, str] = dataclasses.field(default_factory=dict)
# The working directory for the process cwd: str = os.getcwd()
class LSPError(Exception): def __init__(self, code: ErrorCodes, message: str) -> None: super().__init__(message) self.code = code
def to_lsp(self) -> StringDict: return {"code": self.code, "message": super().__str__()}
@classmethod def from_lsp(cls, d: StringDict) -> "LSPError": return LSPError(d["code"], d["message"])
def __str__(self) -> str: return f"{super().__str__()} ({self.code})"
def make_response(request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "result": params}
def make_error_response(request_id: Any, err: LSPError) -> StringDict: return {"jsonrpc": "2.0", "id": request_id, "error": err.to_lsp()}
def make_notification(method: str, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "params": params}
def make_request(method: str, request_id: Any, params: PayloadLike) -> StringDict: return {"jsonrpc": "2.0", "method": method, "id": request_id, "params": params}
class StopLoopException(Exception): pass
def create_message(payload: PayloadLike): body = json.dumps(payload, check_circular=False, ensure_ascii=False, separators=(",", ":")).encode(ENCODING) return ( f"Content-Length: {len(body)}\r\n".encode(ENCODING), "Content-Type: application/vscode-jsonrpc; charset=utf-8\r\n\r\n".encode(ENCODING), body, )
class MessageType: error = 1 warning = 2 info = 3 log = 4
def content_length(line: bytes) -> int | None: if line.startswith(b"Content-Length: "): _, value = line.split(b"Content-Length: ") value = value.strip() try: return int(value) except ValueError: raise ValueError(f"Invalid Content-Length header: {value}") return Noneprojects/ui/serena-new/src/solidlsp/language_servers/intelephense.pyAdded+191
projects/ui/serena-new/src/solidlsp/language_servers/jedi_server.pyAdded+198
projects/ui/serena-new/src/solidlsp/language_servers/kotlin_language_server.pyAdded+469
projects/ui/serena-new/src/solidlsp/language_servers/lua_ls.pyAdded+297
projects/ui/serena-new/src/solidlsp/language_servers/nixd_ls.pyAdded+396
projects/ui/serena-new/src/solidlsp/language_servers/omnisharp.pyAdded+380
projects/ui/serena-new/src/solidlsp/language_servers/pyright_server.pyAdded+202
projects/ui/serena-new/src/solidlsp/language_servers/r_language_server.pyAdded+172
projects/ui/serena-new/src/solidlsp/language_servers/ruby_lsp.pyAdded+442
projects/ui/serena-new/src/solidlsp/language_servers/rust_analyzer.pyAdded+639
projects/ui/serena-new/src/solidlsp/language_servers/solargraph.pyAdded+373
projects/ui/serena-new/src/solidlsp/language_servers/sourcekit_lsp.pyAdded+358
projects/ui/serena-new/src/solidlsp/language_servers/terraform_ls.pyAdded+214
projects/ui/serena-new/src/solidlsp/language_servers/typescript_language_server.pyAdded+253
projects/ui/serena-new/src/solidlsp/language_servers/vts_language_server.pyAdded+235
projects/ui/serena-new/src/solidlsp/language_servers/zls.pyAdded+252
projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_constants.pyAdded+69
projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_requests.pyAdded+561
projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/lsp_types.pyAdded
projects/ui/serena-new/src/solidlsp/lsp_protocol_handler/server.pyAdded+122