Documentation
¶
Overview ¶
Package lsp runs language servers over stdio and turns their diagnostics into post write lint verdicts
Index ¶
- Constants
- Variables
- func AsDiskRead(text string) string
- func AtExitShutdown()
- func BinDir(rt *Runtime) (string, error)
- func ClassifyMessage(msg any) (string, any)
- func DetectStatus(rt *Runtime, pkg string) (string, error)
- func DiagnosticKey(d map[string]any) (string, error)
- func EncodeMessage(obj any) ([]byte, error)
- func ExistingBinary(rt *Runtime, name string) (string, error)
- func FileURI(path string) (string, error)
- func FindNodeExecutable(rt *Runtime, command string) (string, error)
- func FormatDiagnostic(d map[string]any, isPrintable func(rune) bool) (string, error)
- func InlineWait(started time.Time) time.Duration
- func LanguageIDFor(path string, srv *ServerDef) string
- func MakeErrorResponse(id any, code int, message string, data any) map[string]any
- func MakeNotification(method string, params any) map[string]any
- func MakeRequest(id int64, method string, params any) map[string]any
- func MakeResponse(id any, result any) map[string]any
- func ParseTrustedWorkspaces(rt *Runtime, value any) []string
- func PythonError(class, text string) error
- func ReadMessage(r *bufio.Reader, decode func(text string) (any, error)) (msg any, ok bool, err error)
- func ReleaseWorkspace(path string) int
- func ReportForFile(filePath string, diagnostics []map[string]any, isPrintable func(rune) bool) (string, error)
- func RunCommand(ctx context.Context, cc CommandContext, args CommandArgs, ...) int
- func SessionDir(rt *Runtime) (string, error)
- func ShiftBaseline(baseline []map[string]any, shift LineShift) ([]map[string]any, error)
- func ShiftDiagnosticRange(diag map[string]any, shift LineShift) (map[string]any, bool, error)
- func ShutdownServices()
- func StaticRegistryHandles(ext string) bool
- func TryInstall(rt *Runtime, pkg, strategy string) (string, error)
- func URIToPath(uri string) string
- type ArgSpec
- type CheckResult
- type Client
- type ClientOptions
- type ClientStatus
- type CommandArgs
- type CommandContext
- type EditFuture
- type JSONDecodeError
- type LineShift
- type Note
- type Opcode
- type Options
- type ProtocolError
- type Recipe
- type RelatedDocuments
- type RequestError
- type RootFn
- type Runtime
- type ServerContext
- type ServerDef
- type Service
- func (s *Service) EnabledFor(filePath string, operatorRoots map[string]bool) bool
- func (s *Service) GetDiagnosticsSync(filePath string, delta bool, timeout time.Duration, shift LineShift, ...) ([]map[string]any, error)
- func (s *Service) GetStatus() Status
- func (s *Service) HandlesExtension(ext string) bool
- func (s *Service) IsActive() bool
- func (s *Service) ReleaseWorkspace(workspaceRoot string) (int, error)
- func (s *Service) Shutdown()
- func (s *Service) SnapshotBaseline(filePath string, operatorRoots map[string]bool) error
- func (s *Service) StartEditCheck(filePath string, preText, postText *string, owner string, carry []Note, ...) (*EditFuture, error)
- type SpawnFn
- type SpawnSpec
- type Status
- type SubcommandSpec
- type TimeoutError
Constants ¶
const ( CommandHelp = "Language Server Protocol management" CommandDescription = "Manage the LSP layer that powers post-write semantic diagnostics in write_file/patch." )
Help and description of the icebath lsp command
const ( InitializeTimeout = 45 * time.Second DiagnosticsDocumentWait = 5 * time.Second DiagnosticsFullWait = 10 * time.Second )
Client wait budgets and retry policy
const ( WriteBudget = 80 * time.Millisecond InlineGrace = 80 * time.Millisecond )
Write latency budget and the verdict cache cap
const ( ErrorContentModified = -32801 ErrorMethodNotFound = -32601 )
LSP error codes the client acts on
const ( KindRequest = "request" KindResponse = "response" KindNotification = "notification" KindInvalid = "invalid" )
Message kinds ClassifyMessage reports
const ( MaxPerFile = 20 MaxTotalChars = 4000 )
Reporter caps on diagnostics per file, block size and attacker controlled fields
const (
DefaultIdleTimeout = 600.0
)
Service lifetime defaults in seconds
const TypescriptSDKPkg = "typescript@6"
TypescriptSDKPkg pins the last TypeScript line that ships a JavaScript SDK
Variables ¶
var InstallRecipes = map[string]Recipe{ "pyright": npmRecipe("pyright", "pyright-langserver"), "typescript-language-server": npmRecipe("typescript-language-server", "typescript-language-server", TypescriptSDKPkg), "@vue/language-server": npmRecipe("@vue/language-server@2", "vue-language-server", TypescriptSDKPkg), "svelte-language-server": npmRecipe("svelte-language-server", "svelteserver"), "@astrojs/language-server": npmRecipe("@astrojs/language-server", "astro-ls"), "yaml-language-server": npmRecipe("yaml-language-server", "yaml-language-server"), "bash-language-server": npmRecipe("bash-language-server", "bash-language-server"), "intelephense": npmRecipe("intelephense", "intelephense"), "dockerfile-language-server-nodejs": npmRecipe("dockerfile-language-server-nodejs", "docker-langserver"), "gopls": {Strategy: "go", Pkg: "golang.org/x/tools/gopls@latest", Bin: "gopls"}, "rust-analyzer": manualRecipe("rust-analyzer"), "clangd": manualRecipe("clangd"), "lua-language-server": manualRecipe("lua-language-server"), "laravel-lsp": manualRecipe("laravel-lsp"), "powershell": manualRecipe("pwsh"), }
InstallRecipes maps a recipe key to its install strategy, package and binary
var LanguageByExt = func() map[string]string { out := map[string]string{} for _, e := range extsByLanguage { for _, ext := range e.exts { out[ext] = e.lang } } return out }()
LanguageByExt maps an extension or basename to its didOpen languageId
var Servers = []*ServerDef{ server("pyright", []string{".py", ".pyi"}, "Python — Microsoft pyright", serverOpts{ markers: []string{"pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "pyrightconfig.json"}, buildSpawn: spawnPyright, multiRoot: true}), server("typescript", []string{".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"}, "JavaScript/TypeScript — typescript-language-server", serverOpts{resolveRoot: rootTypescript, buildSpawn: spawnTypescript, seed: true}), server("vue-language-server", []string{".vue"}, "Vue.js — @vue/language-server", serverOpts{resolveRoot: rootTypescript, buildSpawn: spawnVue}), server("svelte-language-server", []string{".svelte"}, "Svelte — svelte-language-server", serverOpts{resolveRoot: rootTypescript, which: []string{"svelteserver", "svelte-language-server"}, args: []string{"--stdio"}, installPkg: "svelte-language-server", untrustedInit: map[string]any{"isTrusted": false}}), server("astro-language-server", []string{".astro"}, "Astro — @astrojs/language-server", serverOpts{resolveRoot: rootTypescript, which: []string{"astro-ls", "astro-language-server"}, args: []string{"--stdio"}, installPkg: "@astrojs/language-server"}), server("gopls", []string{".go"}, "Go — gopls", serverOpts{markers: []string{"go.work", "go.mod", "go.sum"}, installPkg: "gopls"}), server("rust-analyzer", []string{".rs"}, "Rust — rust-analyzer", serverOpts{markers: []string{"Cargo.toml", "Cargo.lock"}, installPkg: "rust-analyzer"}), server("clangd", []string{".c", ".cpp", ".cc", ".cxx", ".h", ".hh", ".hpp", ".hxx"}, "C/C++ — clangd", serverOpts{ markers: []string{"compile_commands.json", "compile_flags.txt", ".clangd"}, args: []string{"--background-index", "--clang-tidy"}, installPkg: "clangd"}), server("bash-language-server", []string{".sh", ".bash", ".zsh", ".ksh"}, "Bash — bash-language-server", serverOpts{buildSpawn: spawnBashLS}), server("yaml-language-server", []string{".yaml", ".yml"}, "YAML — yaml-language-server", serverOpts{ args: []string{"--stdio"}, installPkg: "yaml-language-server"}), server("lua-language-server", []string{".lua"}, "Lua — lua-language-server", serverOpts{ markers: []string{".luarc.json", ".luarc.jsonc", ".luacheckrc", ".stylua.toml", "stylua.toml", "selene.toml", "selene.yml"}, installPkg: "lua-language-server"}), server("laravel-lsp", []string{".blade.php"}, "Laravel Blade — laravel-lsp (manual: composer global require laravel/lsp)", serverOpts{markers: []string{"artisan", "composer.json", "composer.lock"}, args: []string{"lsp"}}), server("intelephense", []string{".php"}, "PHP — intelephense", serverOpts{markers: []string{"composer.json", "composer.lock", ".php-version"}, args: []string{"--stdio"}, installPkg: "intelephense", baseInit: map[string]any{"telemetry": map[string]any{"enabled": false}}}), server("ocaml-lsp", []string{".ml", ".mli"}, "OCaml — ocaml-lsp", serverOpts{markers: []string{"dune-project", "dune-workspace", ".merlin", "opam"}, which: []string{"ocamllsp"}}), server("dockerfile-ls", []string{".dockerfile", "Dockerfile"}, "Dockerfile — dockerfile-language-server-nodejs", serverOpts{ which: []string{"docker-langserver"}, args: []string{"--stdio"}, installPkg: "dockerfile-language-server-nodejs"}), server("terraform-ls", []string{".tf", ".tfvars"}, "Terraform — terraform-ls", serverOpts{markers: []string{".terraform.lock.hcl", "terraform.tfstate"}, args: []string{"serve"}, baseInit: map[string]any{"experimentalFeatures": map[string]any{"prefillRequiredFields": true, "validateOnSave": true}}}), server("dart", []string{".dart"}, "Dart — built-in language server", serverOpts{markers: []string{"pubspec.yaml", "analysis_options.yaml"}, args: []string{"language-server", "--lsp"}}), server("haskell-language-server", []string{".hs", ".lhs"}, "Haskell — haskell-language-server", serverOpts{ markers: []string{"stack.yaml", "cabal.project", "hie.yaml"}, which: []string{"haskell-language-server-wrapper", "haskell-language-server"}, args: []string{"--lsp"}}), server("julia", []string{".jl"}, "Julia — LanguageServer.jl", serverOpts{markers: []string{"Project.toml", "Manifest.toml"}, args: []string{"--startup-file=no", "--history-file=no", "-e", "using LanguageServer; runserver()"}}), server("clojure-lsp", []string{".clj", ".cljs", ".cljc", ".edn"}, "Clojure — clojure-lsp", serverOpts{ markers: []string{"deps.edn", "project.clj", "shadow-cljs.edn", "bb.edn", "build.boot"}, args: []string{"listen"}}), server("nixd", []string{".nix"}, "Nix — nixd", serverOpts{resolveRoot: func(fp, ws string) string { if r := workspaces.NearestRoot(fp, []string{"flake.nix"}, nil, ""); r != "" { return r } return ws }}), server("zls", []string{".zig", ".zon"}, "Zig — zls", serverOpts{markers: []string{"build.zig"}}), server("gleam", []string{".gleam"}, "Gleam — built-in language server", serverOpts{markers: []string{"gleam.toml"}, args: []string{"lsp"}}), server("elixir-ls", []string{".ex", ".exs"}, "Elixir — elixir-ls", serverOpts{markers: []string{"mix.exs", "mix.lock"}, which: []string{"elixir-ls", "language_server.sh"}}), server("prisma", []string{".prisma"}, "Prisma — built-in language server", serverOpts{markers: []string{"schema.prisma", "prisma/schema.prisma"}, args: []string{"language-server"}}), server("kotlin-language-server", []string{".kt", ".kts"}, "Kotlin — kotlin-language-server", serverOpts{ markers: []string{"settings.gradle", "settings.gradle.kts", "build.gradle", "build.gradle.kts", "pom.xml"}}), server("jdtls", []string{".java"}, "Java — Eclipse JDT Language Server", serverOpts{ markers: []string{"pom.xml", "build.gradle", "build.gradle.kts", ".project", ".classpath", "settings.gradle"}}), server("powershell", []string{".ps1", ".psm1", ".psd1"}, "PowerShell — PowerShellEditorServices (manual bundle)", serverOpts{ markers: []string{"PSScriptAnalyzerSettings.psd1"}, buildSpawn: spawnPowershellES}), }
Servers is the built in registry, searched in order
var Subcommands = []SubcommandSpec{ {"status", "Show LSP service status", &ArgSpec{"--json", "Emit machine-readable JSON", true}}, {"list", "List supported language servers", &ArgSpec{"--installed-only", "Only show servers whose binary is currently available", true}}, {"install", "Install a server binary", &ArgSpec{"server", "Server id (e.g. pyright, gopls)", false}}, {"install-all", "Install every server with a known auto-install recipe", &ArgSpec{"--include-manual", "Even attempt servers marked manual-install (best effort)", true}}, {"restart", "Tear down running LSP clients (next edit re-spawns)", nil}, {"which", "Print binary path for a server", &ArgSpec{"server", "Server id", false}}, }
Subcommands lists the icebath lsp subcommands in help order
var UntrustedSafeServers = map[string]bool{ "pyright": true, "typescript": true, "svelte-language-server": true, "bash-language-server": true, "yaml-language-server": true, "dockerfile-ls": true, "intelephense": true, "clangd": true, }
UntrustedSafeServers are the only servers that start in a workspace the operator has not trusted
Functions ¶
func AsDiskRead ¶
AsDiskRead returns a text as a utf-8-sig replace read with universal newlines would return its file
func AtExitShutdown ¶
func AtExitShutdown()
AtExitShutdown runs ShutdownServices for an exit hook, logging instead of propagating any failure
func ClassifyMessage ¶
ClassifyMessage names a message kind with its id for requests and responses or its method for notifications
func DetectStatus ¶
DetectStatus reports installed, missing or manual-only for a recipe key without spawning anything
func DiagnosticKey ¶
DiagnosticKey is the content equality key of severity, code, source, message and range
func EncodeMessage ¶
EncodeMessage frames an envelope as compact UTF-8 JSON behind an exact Content-Length header
func ExistingBinary ¶
ExistingBinary probes the staging dir, npm's bin dir on Windows, the Python tool envs, then PATH
func FindNodeExecutable ¶
Managed node, npm or npx or a caller owned tool path, empty when PM has not installed it
func FormatDiagnostic ¶
FormatDiagnostic renders one diagnostic on one line with sanitized fields and 1 based positions
func InlineWait ¶
InlineWait returns how long a write may still wait for its verdict, the grace when its start is unknown
func LanguageIDFor ¶
LanguageIDFor returns the didOpen languageId, a custom server's own id winning
func MakeErrorResponse ¶
MakeErrorResponse builds a JSON-RPC error response envelope
func MakeNotification ¶
MakeNotification builds a JSON-RPC notification envelope without an id
func MakeRequest ¶
MakeRequest builds a JSON-RPC request envelope
func MakeResponse ¶
MakeResponse builds a JSON-RPC success response envelope
func ParseTrustedWorkspaces ¶
ParseTrustedWorkspaces reads lsp.trusted_workspaces, a malformed value trusting nothing extra
func PythonError ¶
PythonError builds the error a Python exception of a class and text stands for
func ReadMessage ¶
func ReadMessage(r *bufio.Reader, decode func(text string) (any, error)) (msg any, ok bool, err error)
ReadMessage reads one framed message decoded by decode, ok false on a clean EOF between messages
func ReleaseWorkspace ¶
ReleaseWorkspace shuts down the clients serving a worktree about to be removed in every started service
func ReportForFile ¶
func ReportForFile(filePath string, diagnostics []map[string]any, isPrintable func(rune) bool) (string, error)
ReportForFile builds the diagnostics block of a file, empty when no error severity diagnostic remains
func RunCommand ¶
func RunCommand(ctx context.Context, cc CommandContext, args CommandArgs, stdout, stderr io.Writer) int
RunCommand runs one icebath lsp subcommand and returns its exit code, 130 when ctx is interrupted first
func SessionDir ¶
SessionDir returns and creates the directory for PowerShellEditorServices session and log files
func ShiftBaseline ¶
ShiftBaseline remaps every baseline diagnostic, dropping deleted entries and non dicts
func ShiftDiagnosticRange ¶
ShiftDiagnosticRange copies a diagnostic with its line range remapped, false when its start line was deleted
func ShutdownServices ¶
func ShutdownServices()
ShutdownServices tears down every started service, idempotent, for the process exit path
func StaticRegistryHandles ¶
StaticRegistryHandles reports whether a built in server lists the extension
func TryInstall ¶
TryInstall installs a package under the auto strategy, else probes, returning the binary or empty
Types ¶
type ArgSpec ¶
ArgSpec is the one optional argument of a subcommand, a store true flag or a positional
type CheckResult ¶
type CheckResult struct {
Diagnostics []map[string]any
HasVerdict bool
BaselineText *string
Superseded bool
Carry []Note
}
CheckResult is one post write verdict, HasVerdict false meaning no verdict in budget
type Client ¶
type Client struct {
ServerID string
WorkspaceRoot string
// contains filtered or unexported fields
}
Client is one language server process serving one workspace root
type ClientOptions ¶
type ClientOptions struct {
ServerID string
WorkspaceRoot string
Command []string
Env map[string]string
Cwd string
InitializationOptions map[string]any
SeedDiagnosticsOnFirstPush bool
}
ClientOptions describe one server process and the workspace root it serves
type ClientStatus ¶
type ClientStatus struct {
ServerID string
WorkspaceRoot string
WorkspaceFolders []string
State string
Running bool
}
ClientStatus is one client row of the service status
type CommandArgs ¶
type CommandArgs struct {
Subcommand string
JSON bool
InstalledOnly bool
IncludeManual bool
Server string
}
CommandArgs are the parsed arguments of icebath lsp
type CommandContext ¶
type CommandContext struct {
Runtime *Runtime
Config func() map[string]any
Service func() (*Service, error)
}
CommandContext is what the command reads from the running profile
type EditFuture ¶
type EditFuture struct {
// contains filtered or unexported fields
}
EditFuture is one scheduled post write check
func (*EditFuture) OnDone ¶
func (f *EditFuture) OnDone(fn func(res *CheckResult, cancelled bool, err error))
OnDone runs fn once when the check finishes or is cancelled, at once when it already has
func (*EditFuture) Wait ¶
func (f *EditFuture) Wait(timeout time.Duration) (*CheckResult, bool, error)
Wait returns the verdict within the timeout, ready false while the check still runs
type JSONDecodeError ¶
type JSONDecodeError struct{ Msg string }
JSONDecodeError is a json.loads decode failure carrying the Python message
func (*JSONDecodeError) Error ¶
func (e *JSONDecodeError) Error() string
type LineShift ¶
LineShift maps a pre edit line to its post edit line, false when the line was deleted
type Note ¶
Note is one undelivered diagnostics note with the pre edit text its verdict was diffed against
type Options ¶
type Options struct {
Enabled bool
WaitMode string
WaitTimeout float64
InstallStrategy string
// Non string install_strategy of the config kept as given for the status report
InstallStrategyRaw any
InstallStrategySet bool
BinaryOverrides map[string][]string
EnvOverrides map[string]map[string]string
InitOverrides map[string]map[string]any
DisabledServers []string
IdleTimeout float64
ExtraServers []*ServerDef
BrokenRetrySeconds float64
WarmupTimeout float64
ExcludeRoots any
TrustedWorkspaces any
OperatorRoots map[string]bool
}
Options configure a service the way the lsp config section does
type ProtocolError ¶
type ProtocolError struct {
// contains filtered or unexported fields
}
ProtocolError reports broken framing or a broken envelope rather than a conformant error response
func (*ProtocolError) Error ¶
func (e *ProtocolError) Error() string
type RelatedDocuments ¶
RelatedDocuments is the relatedDocuments object of a pull response with its uris in server order
type RequestError ¶
type RequestError struct {
Code int
Message string
Data any
// contains filtered or unexported fields
}
RequestError is a JSON-RPC error response carrying code, message and data
func NewRequestError ¶
func NewRequestError(code int, message string, data any) *RequestError
NewRequestError builds the error a JSON-RPC error response raises
func (*RequestError) Error ¶
func (e *RequestError) Error() string
type RootFn ¶
RootFn resolves the per server project root for a file in a workspace, empty to skip the file
type Runtime ¶
type Runtime struct {
Home string
Log *slog.Logger
Config func() map[string]any
EnvFor func(names []string, base map[string]string) map[string]string
EnsureEnv func(name string, base map[string]string) (map[string]string, error)
InstalledBinary func(name string) (string, bool)
PythonTool func(name, bin string) (string, bool, error)
EnsurePythonTool func(name string, requirements []string, bin string, timeout time.Duration) (string, error)
SubprocessEnv func() map[string]string
DelegatedChildEnv func(child map[string]string) map[string]string
OwnProcessGroups func(pgids []int)
RegisterChild func(ctx context.Context, pid int, purpose string) bool
ReleaseProcessGroupOnceEmpty func(pgid int, poll func(), timeout time.Duration) bool
Opcodes func(a, b []string) []Opcode
DecodeJSON func(text string) (any, error)
// Ids under lsp.servers in the order the config file declares them
ServerOrder func() []string
}
Runtime carries the host services the LSP layer reaches through its caller
type ServerContext ¶
type ServerContext struct {
WorkspaceRoot string
InstallStrategy string
BinaryOverrides map[string][]string
EnvOverrides map[string]map[string]string
InitOverrides map[string]map[string]any
Trusted bool
Runtime *Runtime
}
ServerContext is the user policy a spawn builder consults
type ServerDef ¶
type ServerDef struct {
ServerID string
Extensions []string
ResolveRoot RootFn
BuildSpawn SpawnFn
SeedFirstPush bool
Description string
MultiRoot bool
LanguageID string
}
ServerDef is one language server entry of the registry
func CustomServers ¶
CustomServers turns config entries declaring extensions and no built in id into user declared servers
func FindServerForFile ¶
FindServerForFile returns the first entry of servers, the built in registry when nil, handling the file
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service owns the language server clients of one profile and the post write checks that use them
func NewService ¶
NewService builds a service and starts its loop and idle reaper when enabled
func ServiceFor ¶
ServiceFor returns the active service of a profile home, building it once on first use, nil when disabled
func ServiceFromConfig ¶
ServiceFromConfig builds a service from the lsp config section the way create_from_config does
func (*Service) EnabledFor ¶
EnabledFor reports whether LSP runs for the file, remembering the calling session's operator roots
func (*Service) GetDiagnosticsSync ¶
func (s *Service) GetDiagnosticsSync(filePath string, delta bool, timeout time.Duration, shift LineShift, operatorRoots map[string]bool) ([]map[string]any, error)
GetDiagnosticsSync opens the file, waits for fresh diagnostics and returns those not in the baseline
func (*Service) HandlesExtension ¶
HandlesExtension reports whether a config declared or built in server claims the extension
func (*Service) ReleaseWorkspace ¶
ReleaseWorkspace shuts down the clients serving a removed worktree or any root beneath it
func (*Service) Shutdown ¶
func (s *Service) Shutdown()
Shutdown tears down every client and stops the loop
func (*Service) SnapshotBaseline ¶
SnapshotBaseline records the current diagnostics of a file as the delta baseline before a write
type SpawnFn ¶
type SpawnFn func(root string, ctx ServerContext) (*SpawnSpec, error)
SpawnFn assembles the spawn command for a root, nil when the binary cannot be found
type SpawnSpec ¶
type SpawnSpec struct {
Command []string
WorkspaceRoot string
Cwd string
Env map[string]string
InitializationOptions map[string]any
SeedDiagnosticsOnFirstPush bool
}
SpawnSpec is the resolved spawn of a server for one root
type Status ¶
type Status struct {
Enabled bool
WaitMode string
WaitTimeout float64
InstallStrategy string
InstallStrategyRaw any
InstallStrategySet bool
Clients []ClientStatus
Broken [][2]string
DisabledServers []string
BrokenRetrySeconds float64
WarmupTimeout float64
ExcludeRoots []string
ExcludeRootsInvalid bool
TrustedWorkspaces []string
UntrustedSkipped [][2]string
}
Status is the service snapshot icebath lsp status renders
type SubcommandSpec ¶
SubcommandSpec is one icebath lsp subcommand in help order
type TimeoutError ¶
type TimeoutError struct {
// contains filtered or unexported fields
}
TimeoutError is a wait that ran out of its budget
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string