From 4f38eb6bca4936f38f5f470a0978fd750a9d6ddd Mon Sep 17 00:00:00 2001 From: lick <2188718831@qq.com> Date: Tue, 24 Nov 2026 05:03:26 -0800 Subject: [PATCH] feat(navigation): add implementation lookup and gutter navigation backend (v0.2.0) --- README.md | 10 +- THIRD_PARTY_NOTICES.md | 6 + cmd/java-navigation/main.go | 5 + docs/releases/v0.2.0.md | 13 + internal/backend/backend.go | 621 +++++++ internal/backend/backend_test.go | 368 ++++ internal/backend/sdk_lock_test.go | 47 + internal/codenav/implementations.go | 490 ++++++ internal/codenav/implementations_test.go | 152 ++ internal/codenav/parse.go | 60 +- internal/lithesdk/lithe/backend.go | 1236 ++++++++++++++ internal/lithesdk/lithe/cancellation.go | 133 ++ internal/lithesdk/lithe/diagnostics.go | 178 ++ internal/lithesdk/lithe/errors.go | 236 +++ internal/lithesdk/lithe/framing.go | 111 ++ internal/lithesdk/lithe/host.go | 1496 +++++++++++++++++ internal/lithesdk/lithe/protocol.go | 355 ++++ internal/lithesdk/lithe/stdio_dup2.go | 30 + internal/lithesdk/lithe/stdio_linux.go | 31 + internal/lithesdk/lithe/stdio_other.go | 13 + internal/lithesdk/lithe/view.go | 343 ++++ internal/lsp/server.go | 119 ++ internal/lsp/server_test.go | 50 +- internal/workspace/workspace.go | 97 ++ .../plugin.json | 28 +- scripts/package.mjs | 13 +- sdk.lock.json | 69 + vendor/LICENSE | 203 +++ 28 files changed, 6484 insertions(+), 29 deletions(-) create mode 100644 docs/releases/v0.2.0.md create mode 100644 internal/backend/backend.go create mode 100644 internal/backend/backend_test.go create mode 100644 internal/backend/sdk_lock_test.go create mode 100644 internal/codenav/implementations.go create mode 100644 internal/codenav/implementations_test.go create mode 100644 internal/lithesdk/lithe/backend.go create mode 100644 internal/lithesdk/lithe/cancellation.go create mode 100644 internal/lithesdk/lithe/diagnostics.go create mode 100644 internal/lithesdk/lithe/errors.go create mode 100644 internal/lithesdk/lithe/framing.go create mode 100644 internal/lithesdk/lithe/host.go create mode 100644 internal/lithesdk/lithe/protocol.go create mode 100644 internal/lithesdk/lithe/stdio_dup2.go create mode 100644 internal/lithesdk/lithe/stdio_linux.go create mode 100644 internal/lithesdk/lithe/stdio_other.go create mode 100644 internal/lithesdk/lithe/view.go create mode 100644 sdk.lock.json create mode 100644 vendor/LICENSE diff --git a/README.md b/README.md index 41a2cd5..04437d3 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ | 功能 | 说明 | | --- | --- | | 跳转到定义 | 类型、方法、构造器、字段、枚举常量、局部变量、参数、类型参数、注解及其属性;按导入、同包、通配导入、嵌套、继承链、调用参数个数和实参类型解析,支持调用链 `a.b().c` 和 `Foo.bar()` | +| 实现 / 父类双向跳转 | 接口/父类向下跳转到实现类与重写方法(`textDocument/implementation`),实现类/重写方法向上跳回接口与父类声明(`javaNavigation/superDeclarations`),并在行首绘制绿色 `I↓`/`I↑` 与蓝色 `O↓`/`O↑` 导航图标 | | Lombok | `@Data`/`@Getter`/`@Setter` 生成的访问器跳到字段,`@Builder`、`@Slf4j`、构造器注解跳到注解本身(与 JDT LS 一致) | | 跳进 JDK | 项目里找不到的名字到本机 JDK 的 `src.zip` 里找,`String`、`List`、`hashCode()` 等都能跳,并能在 JDK 源码里继续跳 | | 跳进依赖库 | Maven 项目的依赖(含传递依赖)从本地仓库读:下载过 `-sources.jar` 的打开源码,否则打开从 `.class` 生成的签名存根(类、成员类、字段、构造器、方法,参数名取自调试信息),并能在里面继续跳;`@Schema(description = ...)`、`log.info(...)`、`StrUtil.isEmpty(...)` 都能跳 | @@ -146,16 +147,19 @@ go run ./cmd/nav-bench -h # 在真实项目上测命中率、延迟和 `testdata/stubs`,并把 `stubFormat` 加一,让旧版本解压的副本不再被复用。 `dist/` 里每个平台一个 zip(`darwin-arm64`、`darwin-x64`、`windows-x64`、`windows-arm64`),包内只有 -`plugin.json`、`bin/java-navigation`(Windows 是 `bin/java-navigation.exe`,对应平台包的 `plugin.json` 也写这个路径)、 -`LICENSE` 和 `THIRD_PARTY_NOTICES.md`。 +`plugin.json`、`bin/java-navigation`(Windows 是 `bin/java-navigation.exe`,对应平台包的 `plugin.json` 为语言服务器与 `--backend` 后端均写这个路径)、 +`LICENSE`、`THIRD_PARTY_NOTICES.md` 和 `vendor/LICENSE`。 -语言服务器可以单独运行调试: +语言服务器和后端都可以单独运行调试: ```sh go run ./cmd/java-navigation --state-dir /tmp/jn-state # 通过 stdin/stdout 说 LSP,日志写 stderr +go run ./cmd/java-navigation --backend # 以 Lithe 插件后端运行(经 litheLogging 上报日志,不写 stderr) go run ./cmd/java-navigation --version ``` +双向导航后端复用随仓固定的 Go SDK(见 `sdk.lock.json`),将高频收集 `javaNavigation.collect` 设为静默成功、用户点击 `javaNavigation.invoke` 作为关键操作由 SDK 自动记 `INFO`,注册或上下文读取失败通过 `degraded` 上报受控类别(`nav.actions_registration_failed`、`nav.contexts_unavailable`),不写本地文件也不输出路径或源码。 + ## 发布 推送与 `plugin.json` 版本一致的 tag `v`,`release.yml` 会打包并创建 GitHub Release。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 80e36fa..99c0f07 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -35,3 +35,9 @@ LIABILITY, 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 THE SOFTWARE. ``` + +## Lithe Plugin Go SDK + +- Source: https://github.com/Lithe-IDEA/Lithe-core-rust (`shared/plugins/sdk/go/lithe`, revision `0d79e17fde389f559bcb3eeeb11baace13895576`) +- Used in: `internal/lithesdk/lithe/` (copied verbatim from upstream without modifications; checksums pinned in `sdk.lock.json`) +- License: see `vendor/LICENSE` diff --git a/cmd/java-navigation/main.go b/cmd/java-navigation/main.go index c5df88b..0925821 100644 --- a/cmd/java-navigation/main.go +++ b/cmd/java-navigation/main.go @@ -12,6 +12,7 @@ import ( "os" "runtime/debug" + "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/backend" "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/deps" "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/jdk" "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/lsp" @@ -36,12 +37,16 @@ func main() { printVersion := flag.Bool("version", false, "print the version and exit") noJDK := flag.Bool("no-jdk", false, "do not navigate into the JDK's sources") noDeps := flag.Bool("no-dependencies", false, "do not navigate into dependency jars (Maven dependencies and the jars the project keeps)") + runBackend := flag.Bool("backend", false, "run as a Lithe plugin backend over stdio") flag.Bool("stdio", true, "speak LSP over standard input and output (the only transport)") flag.Parse() if *printVersion { fmt.Println("java-navigation", version) return } + if *runBackend { + os.Exit(backend.Run(version)) + } // Standard output carries the protocol; diagnostics go to standard error, // which the host records in the server's log. logger := log.New(os.Stderr, "java-navigation: ", log.LstdFlags|log.Lmsgprefix) diff --git a/docs/releases/v0.2.0.md b/docs/releases/v0.2.0.md new file mode 100644 index 0000000..0ae7403 --- /dev/null +++ b/docs/releases/v0.2.0.md @@ -0,0 +1,13 @@ +# Java Support Lite 0.2.0 + +## 中文 + +- 新增接口、父类、方法与实现类/子类之间的双向跳转:语言服务器实现 `textDocument/implementation`、`javaNavigation/superDeclarations` 与 `javaNavigation/markers`,支持双向查找与反向子类型关系解析。 +- 通过同二进制 `--backend` 轻量后端向编辑器行号栏提供语义导航图标:绿色 `I↓` / `I↑`(接口实现)与蓝色 `O↓` / `O↑`(继承重写),并按宿主能力在旧版宿主上自动回退为通用导航图标;需要 Lithe 桌面端 0.8.17 或更高版本以获得完整交互体验。 + +--- + +## English + +- Add bidirectional navigation between interfaces, superclasses, methods, and their implementations/subclasses: implement `textDocument/implementation`, `javaNavigation/superDeclarations`, and `javaNavigation/markers` with reverse subtype graph resolution. +- Provide IDEA-style editor gutter icons (`I↓` / `I↑` in green for interface implementations and `O↓` / `O↑` in blue for inheritance overrides) via the single-binary `--backend` mode, falling back to generic navigation icons on older hosts; Lithe Desktop 0.8.17 or later is recommended for full gutter icon support. diff --git a/internal/backend/backend.go b/internal/backend/backend.go new file mode 100644 index 0000000..8249fc1 --- /dev/null +++ b/internal/backend/backend.go @@ -0,0 +1,621 @@ +// Package backend implements the Lithe plugin-backend process mode +// (`--backend`) for Java Support Lite, registering bidirectional +// inheritance/implementation gutter actions via editor/registerActions. +package backend + +import ( + "encoding/json" + "errors" + "fmt" + "net/url" + "path" + "strings" + "sync" + "time" + + "github.com/Lithe-IDEA/lithe-plugin-java-navigation/internal/lithesdk/lithe" +) + +const ( + // BackendName is reported as serverInfo.name. + BackendName = "java-navigation-backend" + + // ServerID matches languageServers[0].languageID in plugin.json. + ServerID = "java" + + // ActionsBindingID identifies the editor actions subscription per context. + ActionsBindingID = "java-navigation.markers" + + // CollectFunctionID is called by the host to collect gutter navigation actions. + CollectFunctionID = "javaNavigation.collect" + + // InvokeFunctionID is called by the host when a user clicks a navigation gutter icon. + InvokeFunctionID = "javaNavigation.invoke" + + // Plugin error codes returned cleanly to the host on failures. + errInvalidParams = "nav.invalid_params" + errContextMissing = "nav.context_missing" + errWorkspaceUnavailable = "nav.workspace_unavailable" + errLanguageServerFailed = "nav.language_server_failed" + + // Controlled degraded diagnostic categories reported through SDK Diagnostics. + catActionsRegistrationFailed = "nav.actions_registration_failed" + catContextsUnavailable = "nav.contexts_unavailable" + + methodDidChangeState = "lithe/host/languageServer/didChangeState" + methodLanguageServerReq = "lithe/host/languageServer/request" + methodLSPImplementation = "textDocument/implementation" + methodLSPSuperDeclaration = "javaNavigation/superDeclarations" + methodLSPMarkers = "javaNavigation/markers" + + collectTimeoutMs = 4000 + invokeTimeoutMs = 5000 + syncRetryAttempts = 20 + syncRetryInterval = 200 * time.Millisecond + maxActionsPerFile = 1000 + notificationOpName = "notification" +) + +type registration struct { + generation uint64 + subscription *lithe.Subscription +} + +// Service manages editor action subscriptions across workspace contexts. +type Service struct { + handle *lithe.BackendHandle + + mu sync.Mutex + registrations map[string]registration + closed bool + stopCh chan struct{} + wg sync.WaitGroup +} + +// Run starts the plugin backend over stdin/stdout and returns its exit code. +func Run(version string) int { + b, err := New(version) + if err != nil { + return 1 + } + return b.Listen() +} + +// New constructs a configured Backend ready to Serve/Listen. +func New(version string) (*lithe.Backend, error) { + b := lithe.NewBackend(BackendName) + if version != "" { + b.Version(version) + } + svc := &Service{ + handle: b.Handle(), + registrations: map[string]registration{}, + stopCh: make(chan struct{}), + } + + if err := b.Function(CollectFunctionID, svc.collect); err != nil { + return nil, err + } + if err := b.SuppressSuccessDiagnostics(CollectFunctionID); err != nil { + return nil, err + } + if err := b.Function(InvokeFunctionID, svc.invoke); err != nil { + return nil, err + } + + b.OnInitialize(func(_ *lithe.Initialize) error { + svc.syncAfterInitialize() + return nil + }) + b.OnContextsChanged(func(_ json.RawMessage) error { + svc.syncContextsReporting() + return nil + }) + if err := b.OnHostNotification(methodDidChangeState, func(params json.RawMessage) error { + svc.didChangeState(params) + return nil + }); err != nil { + return nil, err + } + b.OnShutdown(func() { + svc.shutdown() + }) + return b, nil +} + +func (s *Service) shutdown() { + s.mu.Lock() + if !s.closed { + s.closed = true + close(s.stopCh) + } + regs := make([]*lithe.Subscription, 0, len(s.registrations)) + for id, reg := range s.registrations { + regs = append(regs, reg.subscription) + delete(s.registrations, id) + } + s.mu.Unlock() + s.wg.Wait() + for _, sub := range regs { + _ = sub.Dispose() + } +} + +func (s *Service) syncAfterInitialize() { + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return + } + s.wg.Add(1) + s.mu.Unlock() + go func() { + defer s.wg.Done() + for attempt := 0; attempt < syncRetryAttempts; attempt++ { + select { + case <-s.stopCh: + return + case <-time.After(syncRetryInterval): + } + failures, err := s.syncContexts() + if err == nil { + if failures > 0 { + _ = s.handle.Diagnostics().Degraded(notificationOpName, catActionsRegistrationFailed, failures) + } + return + } + if isSessionStoppedError(err) { + return + } + } + _ = s.handle.Diagnostics().Degraded(notificationOpName, catContextsUnavailable, 1) + }() +} + +func (s *Service) didChangeState(params json.RawMessage) { + var ev struct { + ServerID string `json:"serverID"` + State string `json:"state"` + Context lithe.WorkspaceContext `json:"context"` + } + if json.Unmarshal(params, &ev) != nil || ev.ServerID != ServerID || ev.State != "running" { + return + } + if id := ev.Context.ID(); id != "" { + s.mu.Lock() + stale, ok := s.registrations[id] + if ok { + delete(s.registrations, id) + } + s.mu.Unlock() + if ok { + _ = stale.subscription.Dispose() + } + } + s.syncContextsReporting() +} + +func (s *Service) syncContextsReporting() { + failures, err := s.syncContexts() + if err != nil { + if !isSessionStoppedError(err) { + _ = s.handle.Diagnostics().Degraded(notificationOpName, catContextsUnavailable, 1) + } + return + } + if failures > 0 { + _ = s.handle.Diagnostics().Degraded(notificationOpName, catActionsRegistrationFailed, failures) + } +} + +func (s *Service) syncContexts() (uint64, error) { + host := s.handle.Host() + raw, err := host.Workspace().ListContexts() + if err != nil { + return 0, err + } + var listed struct { + Contexts []json.RawMessage `json:"contexts"` + } + if json.Unmarshal(raw, &listed) != nil { + return 0, errors.New("invalid contexts payload") + } + + s.mu.Lock() + if s.closed { + s.mu.Unlock() + return 0, nil + } + seen := map[string]bool{} + var toDispose []*lithe.Subscription + var toRegister []lithe.WorkspaceContext + for _, entry := range listed.Contexts { + var ref lithe.WorkspaceContext + if json.Unmarshal(entry, &ref) != nil { + continue + } + id := ref.ID() + seen[id] = true + if existing, ok := s.registrations[id]; ok { + if existing.generation == ref.Generation() { + continue + } + toDispose = append(toDispose, existing.subscription) + delete(s.registrations, id) + } + toRegister = append(toRegister, ref) + } + for id, existing := range s.registrations { + if !seen[id] { + toDispose = append(toDispose, existing.subscription) + delete(s.registrations, id) + } + } + s.mu.Unlock() + + for _, sub := range toDispose { + _ = sub.Dispose() + } + + var failures uint64 + for _, ref := range toRegister { + sub, err := host.Editor().RegisterActions(ref, map[string]any{ + "id": ActionsBindingID, + "function": CollectFunctionID, + "selector": map[string]any{ + "fileExtensions": []string{"java"}, + "fileNames": []string{}, + }, + }) + if err != nil { + if isSessionStoppedError(err) { + return failures, err + } + failures++ + continue + } + s.mu.Lock() + if s.closed { + s.mu.Unlock() + _ = sub.Dispose() + return failures, nil + } + s.registrations[ref.ID()] = registration{generation: ref.Generation(), subscription: sub} + s.mu.Unlock() + } + return failures, nil +} + +type lspMarkerTarget struct { + Name string `json:"name"` +} + +type lspMarkerItem struct { + Line int `json:"line"` + Character int `json:"character"` + Direction string `json:"direction"` + Relation string `json:"relation"` + Targets []lspMarkerTarget `json:"targets"` +} + +func (s *Service) collect(params json.RawMessage, call *lithe.Context) (any, error) { + if err := call.CheckCancelled(); err != nil { + return nil, err + } + ref := call.WorkspaceContext() + if ref == nil { + return nil, lithe.NewPluginError(errContextMissing, "The call names no workspace.") + } + var req struct { + Document struct { + Path string `json:"path"` + } `json:"document"` + Text string `json:"text"` + } + if json.Unmarshal(params, &req) != nil || req.Document.Path == "" { + return nil, lithe.NewPluginError(errInvalidParams, "The document has no path.") + } + + root, err := workspaceRoot(call.Host(), *ref) + if err != nil { + return nil, err + } + docURI, err := documentFileURI(root, req.Document.Path) + if err != nil { + return nil, err + } + + lspParams := map[string]any{ + "textDocument": map[string]any{"uri": docURI}, + } + if req.Text != "" { + lspParams["text"] = req.Text + } + raw, err := lsRequest(call.Host(), *ref, methodLSPMarkers, lspParams, collectTimeoutMs) + if err != nil { + if isCancelledError(err) { + return nil, lithe.ErrCancelled + } + if isTransientHostError(err) { + return map[string]any{"actions": []any{}}, nil + } + return nil, lithe.NewPluginError(errLanguageServerFailed, "The language server failed to collect navigation markers.") + } + + var resp struct { + Markers []lspMarkerItem `json:"markers"` + } + if len(raw) > 0 && json.Unmarshal(raw, &resp) != nil { + return map[string]any{"actions": []any{}}, nil + } + + semantic := supportsSemanticIcons(call.Host()) + actions := make([]map[string]any, 0, min(len(resp.Markers), maxActionsPerFile)) + for _, m := range resp.Markers { + if len(actions) >= maxActionsPerFile { + break + } + if m.Line < 0 || (m.Direction != "down" && m.Direction != "up") { + continue + } + oneLine := m.Line + 1 + actions = append(actions, map[string]any{ + "id": fmt.Sprintf("nav-%s-%d", m.Direction, m.Line), + "range": map[string]any{ + "start": map[string]any{"line": oneLine, "column": 1}, + "end": map[string]any{"line": oneLine, "column": 1}, + }, + "title": formatMarkerTitle(m.Direction, m.Relation, m.Targets), + "icon": selectIcon(semantic, m.Direction, m.Relation), + "invoke": map[string]any{ + "functionID": InvokeFunctionID, + "params": map[string]any{ + "uri": docURI, + "line": m.Line, + "character": m.Character, + "direction": m.Direction, + }, + }, + }) + } + return map[string]any{"actions": actions}, nil +} + +func (s *Service) invoke(params json.RawMessage, call *lithe.Context) (any, error) { + if err := call.CheckCancelled(); err != nil { + return nil, err + } + ref := call.WorkspaceContext() + if ref == nil { + return nil, lithe.NewPluginError(errContextMissing, "The call names no workspace.") + } + var req struct { + Data struct { + URI string `json:"uri"` + Line *int `json:"line"` + Character *int `json:"character"` + Direction string `json:"direction"` + } `json:"data"` + } + if json.Unmarshal(params, &req) != nil || req.Data.URI == "" || req.Data.Line == nil || req.Data.Character == nil { + return nil, lithe.NewPluginError(errInvalidParams, "The click carries incomplete navigation data.") + } + + var lspMethod string + switch req.Data.Direction { + case "down": + lspMethod = methodLSPImplementation + case "up": + lspMethod = methodLSPSuperDeclaration + default: + return nil, lithe.NewPluginError(errInvalidParams, "The navigation direction is invalid.") + } + + raw, err := lsRequest(call.Host(), *ref, lspMethod, map[string]any{ + "textDocument": map[string]any{"uri": req.Data.URI}, + "position": map[string]any{ + "line": *req.Data.Line, + "character": *req.Data.Character, + }, + }, invokeTimeoutMs) + if err != nil { + if isCancelledError(err) { + return nil, lithe.ErrCancelled + } + return nil, lithe.NewPluginError(errLanguageServerFailed, "The language server failed to resolve navigation targets.") + } + + var locations []json.RawMessage + if len(raw) > 0 && string(raw) != "null" { + if err := json.Unmarshal(raw, &locations); err != nil { + var single json.RawMessage + if json.Unmarshal(raw, &single) == nil && len(single) > 0 && string(single) != "null" { + locations = []json.RawMessage{single} + } + } + } + if locations == nil { + locations = []json.RawMessage{} + } + return map[string]any{ + "reveal": map[string]any{ + "locations": locations, + }, + }, nil +} + +func lsRequest(host *lithe.Host, ref lithe.WorkspaceContext, method string, params any, timeoutMs int) (json.RawMessage, error) { + raw, err := host.Request(methodLanguageServerReq, map[string]any{ + "context": ref, + "serverID": ServerID, + "method": method, + "params": params, + "timeoutMilliseconds": timeoutMs, + }) + if err != nil { + return nil, err + } + var env struct { + Value json.RawMessage `json:"value"` + } + if json.Unmarshal(raw, &env) != nil { + return nil, nil + } + return env.Value, nil +} + +func workspaceRoot(host *lithe.Host, ref lithe.WorkspaceContext) (string, error) { + raw, err := host.Workspace().GetContext(ref) + if err != nil { + if isCancelledError(err) { + return "", lithe.ErrCancelled + } + return "", lithe.NewPluginError(errWorkspaceUnavailable, "The workspace context is unavailable.") + } + var ctx struct { + Folders []struct { + Path string `json:"path"` + } `json:"folders"` + } + if json.Unmarshal(raw, &ctx) != nil || len(ctx.Folders) == 0 || ctx.Folders[0].Path == "" { + return "", lithe.NewPluginError(errWorkspaceUnavailable, "The workspace has no local folder.") + } + return ctx.Folders[0].Path, nil +} + +func supportsSemanticIcons(host *lithe.Host) bool { + raw, err := host.Capabilities() + if err != nil { + return false + } + var caps struct { + Services struct { + Editor struct { + Options struct { + ActionIcons []string `json:"actionIcons"` + } `json:"options"` + } `json:"editor"` + } `json:"services"` + } + if json.Unmarshal(raw, &caps) != nil { + return false + } + icons := map[string]bool{} + for _, icon := range caps.Services.Editor.Options.ActionIcons { + icons[icon] = true + } + return icons["navigate-implemented"] && + icons["navigate-implementing"] && + icons["navigate-overridden"] && + icons["navigate-overriding"] +} + +func selectIcon(semantic bool, direction, relation string) string { + if !semantic { + if direction == "down" { + return "navigate-implementations" + } + return "navigate-super" + } + switch { + case direction == "down" && relation == "interface": + return "navigate-implemented" + case direction == "up" && relation == "interface": + return "navigate-implementing" + case direction == "down": + return "navigate-overridden" + default: + return "navigate-overriding" + } +} + +func formatMarkerTitle(direction, relation string, targets []lspMarkerTarget) string { + var verb string + switch { + case direction == "down" && relation == "interface": + verb = "Implemented by" + case direction == "down": + verb = "Overridden by" + case direction == "up" && relation == "interface": + verb = "Implements" + default: + verb = "Overrides" + } + var labels []string + seen := map[string]bool{} + for _, t := range targets { + name := strings.TrimSpace(t.Name) + if name != "" && !seen[name] { + seen[name] = true + labels = append(labels, name) + } + } + switch len(labels) { + case 0: + return fmt.Sprintf("%s (%d)", verb, len(targets)) + case 1, 2, 3: + return verb + " " + strings.Join(labels, ", ") + default: + return fmt.Sprintf("%s %s (+%d)", verb, strings.Join(labels[:2], ", "), len(labels)-2) + } +} + +// documentFileURI converts a workspace root folder and workspace-relative +// slash path into a canonical file:// URI for both POSIX and Windows paths. +func documentFileURI(root, rel string) (string, error) { + cleanRel := strings.TrimLeft(strings.ReplaceAll(rel, "\\", "/"), "/") + if cleanRel == "" { + return "", lithe.NewPluginError(errInvalidParams, "The document path is empty.") + } + slashRoot := strings.ReplaceAll(root, "\\", "/") + if strings.HasPrefix(slashRoot, "//") { + trimmed := strings.TrimPrefix(slashRoot, "//") + host, rest, ok := strings.Cut(trimmed, "/") + if !ok || host == "" { + return "", lithe.NewPluginError(errWorkspaceUnavailable, "Invalid UNC workspace root.") + } + p := path.Clean("/" + rest + "/" + cleanRel) + return (&url.URL{Scheme: "file", Host: host, Path: p}).String(), nil + } + if len(slashRoot) >= 2 && slashRoot[1] == ':' && ((slashRoot[0] >= 'A' && slashRoot[0] <= 'Z') || (slashRoot[0] >= 'a' && slashRoot[0] <= 'z')) { + drive := strings.ToUpper(slashRoot[:1]) + ":" + rest := strings.TrimPrefix(slashRoot[2:], "/") + joined := path.Clean("/" + rest + "/" + cleanRel) + return (&url.URL{Scheme: "file", Path: "/" + drive + joined}).String(), nil + } + if !strings.HasPrefix(slashRoot, "/") { + return "", lithe.NewPluginError(errWorkspaceUnavailable, "Workspace root must be an absolute path.") + } + joined := path.Clean(slashRoot + "/" + cleanRel) + return (&url.URL{Scheme: "file", Path: joined}).String(), nil +} + +func isCancelledError(err error) bool { + if errors.Is(err, lithe.ErrCancelled) { + return true + } + var sdkErr *lithe.SdkError + return errors.As(err, &sdkErr) && sdkErr.Code() == lithe.CodeCallCancelled +} + +func isSessionStoppedError(err error) bool { + var sdkErr *lithe.SdkError + return errors.As(err, &sdkErr) && (sdkErr.Code() == lithe.CodeSessionClosed || sdkErr.Code() == "sdk.session.notReady") +} + +func isTransientHostError(err error) bool { + var sdkErr *lithe.SdkError + if !errors.As(err, &sdkErr) { + return false + } + switch sdkErr.Code() { + case "plugin.host.languageServerUnavailable", + "plugin.host.busy", + "plugin.host.timeout", + "plugin.host.cancelled", + "plugin.host.languageServerError": + return true + default: + return false + } +} diff --git a/internal/backend/backend_test.go b/internal/backend/backend_test.go new file mode 100644 index 0000000..700e1a4 --- /dev/null +++ b/internal/backend/backend_test.go @@ -0,0 +1,368 @@ +package backend + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +const testTimeout = 10 * time.Second + +type mockHost struct { + t *testing.T + in *io.PipeWriter + frames chan map[string]any + done chan int + + mu sync.Mutex + msgs []map[string]any +} + +func startBackendSession(t *testing.T, handler func(method string, params map[string]any) (any, *rpcErr)) *mockHost { + t.Helper() + b, err := New("0.2.0-test") + if err != nil { + t.Fatalf("backend.New: %v", err) + } + backendInR, hostToBackendW := io.Pipe() + hostFromBackendR, backendOutW := io.Pipe() + + m := &mockHost{ + t: t, + in: hostToBackendW, + frames: make(chan map[string]any, 64), + done: make(chan int, 1), + } + go func() { + code := b.Serve(backendInR, backendOutW) + _ = backendOutW.Close() + m.done <- code + }() + go func() { + r := bufio.NewReader(hostFromBackendR) + for { + msg, err := readFrame(r) + if err != nil { + close(m.frames) + return + } + m.frames <- msg + } + }() + t.Cleanup(func() { + _ = hostToBackendW.Close() + select { + case <-m.done: + case <-time.After(testTimeout): + t.Error("backend did not exit") + } + }) + _ = handler + return m +} + +func readFrame(r *bufio.Reader) (map[string]any, error) { + length := 0 + for { + line, err := r.ReadString('\n') + if err != nil { + return nil, err + } + line = strings.TrimRight(line, "\r\n") + if line == "" { + break + } + if v, ok := strings.CutPrefix(line, "Content-Length: "); ok { + length, _ = strconv.Atoi(v) + } + } + buf := make([]byte, length) + if _, err := io.ReadFull(r, buf); err != nil { + return nil, err + } + var out map[string]any + if err := json.Unmarshal(buf, &out); err != nil { + return nil, err + } + return out, nil +} + +type rpcErr struct { + code int + msg string +} + +func (m *mockHost) writeJSON(v any) { + m.t.Helper() + b, err := json.Marshal(v) + if err != nil { + m.t.Fatal(err) + } + if _, err := fmt.Fprintf(m.in, "Content-Length: %d\r\n\r\n%s", len(b), b); err != nil { + m.t.Fatal(err) + } +} + +func (m *mockHost) notify(method string, params any) { + m.writeJSON(map[string]any{"jsonrpc": "2.0", "method": method, "params": params}) +} + +func (m *mockHost) request(id any, method string, params any) { + m.writeJSON(map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}) +} + +func (m *mockHost) runUntil( + stop func(frame map[string]any) bool, + onRequest func(method string, params map[string]any) any, +) (map[string]any, []map[string]any) { + m.t.Helper() + var logs []map[string]any + deadline := time.After(testTimeout) + for { + select { + case frame, ok := <-m.frames: + if !ok { + m.t.Fatal("backend closed protocol stream prematurely") + } + method, _ := frame["method"].(string) + if method == "lithe/log" { + if p, ok := frame["params"].(map[string]any); ok { + logs = append(logs, p) + } + continue + } + if method != "" { + answer := onRequest(method, mapField(frame, "params")) + done := stop(frame) + m.writeJSON(map[string]any{"jsonrpc": "2.0", "id": frame["id"], "result": answer}) + if done { + return frame, logs + } + continue + } + if stop(frame) { + return frame, logs + } + case <-deadline: + m.t.Fatal("timed out waiting for backend frame") + } + } +} + +func mapField(m map[string]any, k string) map[string]any { + v, _ := m[k].(map[string]any) + return v +} + +func TestBackendRegistrationCollectAndInvokeWithQuietLogging(t *testing.T) { + m := startBackendSession(t, nil) + + ctxRef := map[string]any{"contextID": "ctx-lite", "generation": 1} + fullCtx := map[string]any{ + "contextID": "ctx-lite", + "generation": 1, + "folders": []any{map[string]any{"rootID": "r1", "path": "/workspace/lite"}}, + } + + m.request(0, "initialize", map[string]any{ + "rootUri": "file:///tmp/state/", + "capabilities": map[string]any{ + "experimental": map[string]any{ + "litheFunctions": map[string]any{"versions": []int{0}}, + "litheLogging": map[string]any{"versions": []int{0}}, + }, + }, + }) + initResp, _ := m.runUntil(func(f map[string]any) bool { return f["id"] == float64(0) }, func(string, map[string]any) any { return nil }) + if initResp["error"] != nil { + t.Fatalf("initialize failed: %+v", initResp) + } + m.notify("initialized", map[string]any{}) + m.notify(methodDidChangeState, map[string]any{ + "serverID": "java", + "state": "running", + "context": ctxRef, + }) + + // Wait for editor/registerActions subscription. + var regParams map[string]any + m.runUntil( + func(f map[string]any) bool { return f["method"] == "lithe/host/editor/registerActions" }, + func(method string, params map[string]any) any { + switch method { + case "lithe/host/workspace/listContexts": + return map[string]any{"contexts": []any{fullCtx}} + case "lithe/host/editor/registerActions": + regParams = params + return map[string]any{"subscriptionID": "sub-1"} + default: + return map[string]any{} + } + }, + ) + if regParams["id"] != ActionsBindingID || regParams["function"] != CollectFunctionID { + t.Fatalf("unexpected registerActions params: %+v", regParams) + } + + // Invoke javaNavigation.collect; verify 4 semantic icons + suppressed INFO log. + m.request(10, "lithe/function/invoke", map[string]any{ + "functionID": CollectFunctionID, + "operationID": "op-collect-1", + "context": ctxRef, + "params": map[string]any{ + "document": map[string]any{"path": "src/App.java"}, + "text": "class Impl implements Greeter { public void greet() {} }\n", + }, + }) + collectResp, collectLogs := m.runUntil( + func(f map[string]any) bool { return f["id"] == float64(10) }, + func(method string, params map[string]any) any { + switch method { + case "lithe/host/workspace/getContext": + return fullCtx + case "lithe/host/getCapabilities": + return map[string]any{ + "services": map[string]any{ + "editor": map[string]any{ + "options": map[string]any{ + "actionIcons": []string{ + "navigate-implemented", + "navigate-implementing", + "navigate-overridden", + "navigate-overriding", + }, + }, + }, + }, + } + case "lithe/host/languageServer/request": + return map[string]any{ + "value": map[string]any{ + "markers": []any{ + map[string]any{ + "line": 0, "character": 6, "endCharacter": 10, + "direction": "up", "relation": "interface", + "targets": []any{map[string]any{"name": "Greeter"}}, + }, + map[string]any{ + "line": 0, "character": 44, "endCharacter": 49, + "direction": "down", "relation": "inheritance", + "targets": []any{map[string]any{"name": "SubImpl"}}, + }, + }, + }, + } + default: + return map[string]any{} + } + }, + ) + result := mapField(collectResp, "result") + actions, _ := result["actions"].([]any) + if len(actions) != 2 { + t.Fatalf("collect actions = %+v, want 2", collectResp) + } + first := actions[0].(map[string]any) + second := actions[1].(map[string]any) + if first["icon"] != "navigate-implementing" || second["icon"] != "navigate-overridden" { + t.Fatalf("unexpected icons: %+v %+v", first["icon"], second["icon"]) + } + for _, lg := range collectLogs { + if lg["kind"] == "operationFinished" && lg["operation"] == CollectFunctionID { + t.Fatalf("collect must suppress operationFinished INFO log: %+v", collectLogs) + } + } + + // Invoke javaNavigation.invoke; verify reveal.locations and INFO log. + invokeSpec := first["invoke"].(map[string]any) + m.request(11, "lithe/function/invoke", map[string]any{ + "functionID": InvokeFunctionID, + "operationID": "op-invoke-1", + "context": ctxRef, + "params": map[string]any{ + "data": invokeSpec["params"], + }, + }) + var requestedMethod string + invokeResp, invokeLogs := m.runUntil( + func(f map[string]any) bool { return f["id"] == float64(11) }, + func(method string, params map[string]any) any { + if method == "lithe/host/languageServer/request" { + requestedMethod, _ = params["method"].(string) + return map[string]any{ + "value": []any{ + map[string]any{ + "uri": "file:///workspace/lite/src/Greeter.java", + "range": map[string]any{ + "start": map[string]any{"line": 0, "character": 17}, + "end": map[string]any{"line": 0, "character": 24}, + }, + }, + }, + } + } + return map[string]any{} + }, + ) + if requestedMethod != methodLSPSuperDeclaration { + t.Fatalf("requested LSP method = %q, want %q", requestedMethod, methodLSPSuperDeclaration) + } + reveal := mapField(mapField(invokeResp, "result"), "reveal") + locs, _ := reveal["locations"].([]any) + if len(locs) != 1 { + t.Fatalf("reveal locations = %+v", invokeResp) + } + sawFinished := false + for _, lg := range invokeLogs { + if lg["kind"] == "operationFinished" && lg["operation"] == InvokeFunctionID { + sawFinished = true + } + } + if !sawFinished { + t.Fatalf("expected operationFinished INFO log for invoke: %+v", invokeLogs) + } + + m.request(99, "shutdown", nil) + m.runUntil(func(f map[string]any) bool { return f["id"] == float64(99) }, func(string, map[string]any) any { + return map[string]any{} + }) + m.notify("exit", nil) + select { + case code := <-m.done: + if code != 0 { + t.Fatalf("backend exit code = %d, want 0", code) + } + m.done <- 0 // for t.Cleanup + case <-time.After(testTimeout): + t.Fatal("backend did not exit cleanly after exit") + } +} + +func TestDocumentFileURIAndLegacyIconFallback(t *testing.T) { + cases := []struct { + root, rel, want string + }{ + {"/workspace/app", "src/Main.java", "file:///workspace/app/src/Main.java"}, + {"/workspace/my app", "src/Main.java", "file:///workspace/my%20app/src/Main.java"}, + {`C:\Users\dev\app`, `src\Main.java`, "file:///C:/Users/dev/app/src/Main.java"}, + {`\\server\share\repo`, `src/Main.java`, "file://server/share/repo/src/Main.java"}, + } + for _, tc := range cases { + got, err := documentFileURI(tc.root, tc.rel) + if err != nil || got != tc.want { + t.Errorf("documentFileURI(%q, %q) = (%q, %v), want %q", tc.root, tc.rel, got, err, tc.want) + } + } + if got := selectIcon(false, "down", "interface"); got != "navigate-implementations" { + t.Errorf("legacy down icon = %q", got) + } + if got := selectIcon(false, "up", "inheritance"); got != "navigate-super" { + t.Errorf("legacy up icon = %q", got) + } +} diff --git a/internal/backend/sdk_lock_test.go b/internal/backend/sdk_lock_test.go new file mode 100644 index 0000000..dad2a1c --- /dev/null +++ b/internal/backend/sdk_lock_test.go @@ -0,0 +1,47 @@ +package backend + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestVendoredGoSDKMatchesLockChecksums(t *testing.T) { + root := filepath.Join("..", "..") + data, err := os.ReadFile(filepath.Join(root, "sdk.lock.json")) + if err != nil { + t.Fatalf("read sdk.lock.json: %v", err) + } + var lock struct { + SchemaVersion int `json:"schemaVersion"` + Source struct { + Repository string `json:"repository"` + Revision string `json:"revision"` + } `json:"source"` + Files []struct { + Upstream string `json:"upstream"` + Path string `json:"path"` + SHA256 string `json:"sha256"` + } `json:"files"` + } + if err := json.Unmarshal(data, &lock); err != nil { + t.Fatalf("parse sdk.lock.json: %v", err) + } + if lock.SchemaVersion != 1 || len(lock.Source.Revision) != 40 || len(lock.Files) == 0 { + t.Fatalf("invalid sdk.lock.json metadata: %+v", lock) + } + for _, f := range lock.Files { + body, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(f.Path))) + if err != nil { + t.Fatalf("missing vendored file %s: %v", f.Path, err) + } + sum := sha256.Sum256(body) + got := hex.EncodeToString(sum[:]) + if got != f.SHA256 { + t.Errorf("%s sha256 = %s, want %s (upstream %s)", f.Path, got, f.SHA256, f.Upstream) + } + } +} diff --git a/internal/codenav/implementations.go b/internal/codenav/implementations.go new file mode 100644 index 0000000..f6bdf86 --- /dev/null +++ b/internal/codenav/implementations.go @@ -0,0 +1,490 @@ +package codenav + +import ( + "sort" + "strings" +) + +// NavTarget describes one resolved target shown in gutter marker tooltips and +// menus without exposing filesystem paths. +type NavTarget struct { + Name string + Location Location +} + +// NavMarker describes one bidirectional inheritance or implementation gutter +// icon for a declaration in a Java file. Line and Column are 0-based (byte +// column, matching Location). +type NavMarker struct { + Line int + Column int + Direction string // "down" or "up" + Relation string // "interface" or "inheritance" + Targets []NavTarget +} + +// Implementations returns all subtypes (for types) or overriding/implementing +// methods (for non-private, non-static, non-final methods) reachable from the +// declaration resolved at byte offset off of src in workspace file path. +func (ix *Index) Implementations(path string, src []byte, off int) []Location { + return ix.implementations(path, false, src, off) +} + +// LibraryImplementations is Implementations for a read-only JDK/dependency file. +func (ix *Index) LibraryImplementations(path string, src []byte, off int) []Location { + return ix.implementations(path, true, src, off) +} + +func (ix *Index) implementations(path string, lib bool, src []byte, off int) []Location { + ps := parseJava(src, path, newInterner(), true) + ps.f.Lib = lib + if !lib { + ix.Put(ps.f) + } + ix.mu.RLock() + defer ix.mu.RUnlock() + + p := &parser{src: src, toks: ps.toks, f: ps.f, in: newInterner()} + q := newQuery(ix, p, ps) + declType, declMember, ok := ix.resolveDeclarationAt(q, ps, off) + if !ok { + return nil + } + rev := ix.reverseSubtypes(q) + if declMember == nil { + if declType.Kind == kAnnotation || declType.Final { + return nil + } + subs := collectSubtypes(rev, declType) + out := make([]Location, 0, len(subs)) + for _, st := range subs { + out = append(out, typeLocation(st, st.Name)) + } + sortLocations(out) + return out + } + if declMember.Kind != kMethod || declMember.Private || declMember.Static || declMember.Final { + return nil + } + subs := collectSubtypes(rev, declMember.Owner) + var out []Location + for _, st := range subs { + for _, sm := range st.Members { + if sm.Kind == kMethod && !sm.Private && !sm.Static && methodsOverrideMatch(declMember, sm) { + out = append(out, memberLocation(sm)) + } + } + } + sortLocations(out) + return out +} + +// SuperDeclarations returns direct supertype declarations (for types) or +// overridden/implemented ancestor method declarations (for methods) at byte +// offset off of src in workspace file path. +func (ix *Index) SuperDeclarations(path string, src []byte, off int) []Location { + return ix.superDeclarations(path, false, src, off) +} + +// LibrarySuperDeclarations is SuperDeclarations for a read-only library file. +func (ix *Index) LibrarySuperDeclarations(path string, src []byte, off int) []Location { + return ix.superDeclarations(path, true, src, off) +} + +func (ix *Index) superDeclarations(path string, lib bool, src []byte, off int) []Location { + ps := parseJava(src, path, newInterner(), true) + ps.f.Lib = lib + if !lib { + ix.Put(ps.f) + } + ix.mu.RLock() + defer ix.mu.RUnlock() + + p := &parser{src: src, toks: ps.toks, f: ps.f, in: newInterner()} + q := newQuery(ix, p, ps) + declType, declMember, ok := ix.resolveDeclarationAt(q, ps, off) + if !ok { + return nil + } + if declMember == nil { + var out []Location + seen := map[*Type]bool{} + for _, st := range q.superTypes(declType) { + if st == nil || st == declType || seen[st] { + continue + } + seen[st] = true + out = append(out, typeLocation(st, st.Name)) + } + sortLocations(out) + return out + } + if declMember.Kind != kMethod || declMember.Private || declMember.Static { + return nil + } + supers := collectSuperMethods(q, declMember, true) + out := make([]Location, 0, len(supers)) + for _, sm := range supers { + out = append(out, memberLocation(sm)) + } + sortLocations(out) + return out +} + +// NavigationMarkers returns all verified bidirectional inheritance and +// implementation gutter markers for the declarations in workspace file path. +func (ix *Index) NavigationMarkers(path string, src []byte) []NavMarker { + return ix.navigationMarkers(path, false, src) +} + +// LibraryNavigationMarkers returns navigation markers for a read-only library file. +func (ix *Index) LibraryNavigationMarkers(path string, src []byte) []NavMarker { + return ix.navigationMarkers(path, true, src) +} + +func (ix *Index) navigationMarkers(path string, lib bool, src []byte) []NavMarker { + ps := parseJava(src, path, newInterner(), false) + ps.f.Lib = lib + if !lib { + ix.Put(ps.f) + } + ix.mu.RLock() + defer ix.mu.RUnlock() + + p := &parser{src: src, toks: ps.toks, f: ps.f, in: newInterner()} + q := newQuery(ix, p, ps) + rev := ix.reverseSubtypes(q) + + var markers []NavMarker + var walk func(t *Type) + walk = func(t *Type) { + // Type downward marker (interface implementations or class subclasses). + if t.Kind == kInterface || (t.Kind == kClass && !t.Final) { + if subs := collectSubtypes(rev, t); len(subs) > 0 { + rel := "inheritance" + if t.Kind == kInterface { + rel = "interface" + } + targets := make([]NavTarget, 0, len(subs)) + for _, st := range subs { + targets = append(targets, NavTarget{Name: st.Name, Location: typeLocation(st, st.Name)}) + } + sortNavTargets(targets) + markers = append(markers, NavMarker{ + Line: int(t.Line), Column: int(t.Col), + Direction: "down", Relation: rel, Targets: targets, + }) + } + } + + // Type upward marker (extends / implements). + superTypes, superRel := resolveTypeSupersWithRelation(q, t) + if len(superTypes) > 0 { + targets := make([]NavTarget, 0, len(superTypes)) + for _, st := range superTypes { + targets = append(targets, NavTarget{Name: st.Name, Location: typeLocation(st, st.Name)}) + } + sortNavTargets(targets) + markers = append(markers, NavMarker{ + Line: int(t.Line), Column: int(t.Col), + Direction: "up", Relation: superRel, Targets: targets, + }) + } + + // Member markers (methods). + for _, m := range t.Members { + if m.Kind != kMethod || m.Private || m.Static { + continue + } + if !m.Final && (t.Kind == kInterface || (t.Kind == kClass && !t.Final)) { + subs := collectSubtypes(rev, t) + var targets []NavTarget + for _, st := range subs { + for _, sm := range st.Members { + if sm.Kind == kMethod && !sm.Private && !sm.Static && methodsOverrideMatch(m, sm) { + targets = append(targets, NavTarget{ + Name: st.Name, + Location: memberLocation(sm), + }) + } + } + } + if len(targets) > 0 { + sortNavTargets(targets) + rel := "inheritance" + if t.Kind == kInterface || m.Abstract { + rel = "interface" + } + markers = append(markers, NavMarker{ + Line: int(m.Line), Column: int(m.Col), + Direction: "down", Relation: rel, Targets: targets, + }) + } + } + + if superMethods := collectSuperMethods(q, m, false); len(superMethods) > 0 { + rel := "inheritance" + targets := make([]NavTarget, 0, len(superMethods)) + for _, sm := range superMethods { + if sm.Owner.Kind == kInterface || sm.Abstract { + rel = "interface" + } + targets = append(targets, NavTarget{ + Name: sm.Owner.Name + "." + sm.Name + "()", + Location: memberLocation(sm), + }) + } + sortNavTargets(targets) + markers = append(markers, NavMarker{ + Line: int(m.Line), Column: int(m.Col), + Direction: "up", Relation: rel, Targets: targets, + }) + } + } + + for _, nested := range t.Nested { + walk(nested) + } + } + + file := ix.files[path] + if file == nil { + file = ps.f + } + for _, t := range file.Types { + walk(t) + } + sort.Slice(markers, func(i, j int) bool { + if markers[i].Line != markers[j].Line { + return markers[i].Line < markers[j].Line + } + return markers[i].Direction < markers[j].Direction + }) + return markers +} + +func (ix *Index) resolveDeclarationAt(q *qctx, ps *parsed, off int) (*Type, *Member, bool) { + p := q.p + ti := -1 + for i, t := range ps.toks { + if int(t.S) <= off && off < int(t.E) { + ti = i + break + } + if int(t.S) > off { + break + } + } + if ti < 0 || !p.ident(ti) || javaKeywords[p.txt(ti)] { + return nil, nil, false + } + hits := q.resolveAt(ti) + if len(hits) == 0 { + return nil, nil, false + } + h := hits[0] + f := ix.fileOf(Location{Path: h.File, Library: h.Lib}) + if f == nil { + return nil, nil, false + } + var walk func(t *Type) (*Type, *Member) + walk = func(t *Type) (*Type, *Member) { + if t.Line == h.Line && t.Col == h.Col { + return t, nil + } + for _, m := range t.Members { + if m.Line == h.Line && m.Col == h.Col { + return t, m + } + } + for _, c := range t.Nested { + if dt, dm := walk(c); dt != nil { + return dt, dm + } + } + return nil, nil + } + for _, t := range f.Types { + if dt, dm := walk(t); dt != nil { + return dt, dm, true + } + } + return nil, nil, false +} + +func (ix *Index) reverseSubtypes(q *qctx) map[*Type][]*Type { + rev := make(map[*Type][]*Type) + var walk func(t *Type) + walk = func(t *Type) { + for _, sup := range q.superTypes(t) { + if sup != nil && sup != t { + rev[sup] = append(rev[sup], t) + } + } + for _, c := range t.Nested { + walk(c) + } + } + for _, f := range ix.files { + for _, t := range f.Types { + walk(t) + } + } + return rev +} + +func collectSubtypes(rev map[*Type][]*Type, root *Type) []*Type { + visited := map[*Type]bool{root: true} + queue := []*Type{root} + var subs []*Type + for len(queue) > 0 { + cur := queue[0] + queue = queue[1:] + for _, child := range rev[cur] { + if visited[child] { + continue + } + visited[child] = true + subs = append(subs, child) + queue = append(queue, child) + } + } + return subs +} + +func resolveTypeSupersWithRelation(q *qctx, t *Type) ([]*Type, string) { + var out []*Type + seen := map[*Type]bool{t: true} + rel := "inheritance" + for _, s := range t.Extends { + if st := q.resolveText(s, t.File, t.Outer); st != nil && !seen[st] { + seen[st] = true + out = append(out, st) + if st.Kind == kInterface { + rel = "interface" + } + } + } + for _, s := range t.Implements { + if st := q.resolveText(s, t.File, t.Outer); st != nil && !seen[st] { + seen[st] = true + out = append(out, st) + rel = "interface" + } + } + return out, rel +} + +// collectSuperMethods walks t's ancestor chain (with cycle guard) and collects +// matching overridden/implemented methods. includeObject covers java.lang.Object +// overrides when requested or for well-known Object methods. +func collectSuperMethods(q *qctx, m *Member, includeObject bool) []*Member { + visited := map[*Type]bool{m.Owner: true} + queue := append([]*Type(nil), q.superTypes(m.Owner)...) + var ancestors []*Type + for len(queue) > 0 && len(visited) < 64 { + cur := queue[0] + queue = queue[1:] + if cur == nil || visited[cur] { + continue + } + visited[cur] = true + ancestors = append(ancestors, cur) + queue = append(queue, q.superTypes(cur)...) + } + if includeObject || isObjectOverridable(m.Name) { + if obj := q.impliedType("java.lang.Object"); obj != nil && !visited[obj] { + ancestors = append(ancestors, obj) + } + } + var found []*Member + seenMember := map[*Member]bool{} + for _, anc := range ancestors { + for _, sm := range anc.Members { + if sm.Kind == kMethod && !sm.Private && !sm.Static && methodsOverrideMatch(sm, m) && !seenMember[sm] { + seenMember[sm] = true + found = append(found, sm) + } + } + } + return found +} + +func isObjectOverridable(name string) bool { + switch name { + case "toString", "equals", "hashCode", "clone", "finalize": + return true + default: + return false + } +} + +func methodsOverrideMatch(base, sub *Member) bool { + if base.Kind != kMethod || sub.Kind != kMethod || base.Name != sub.Name { + return false + } + if base.Arity != sub.Arity || base.Varargs != sub.Varargs { + return false + } + if base.Params == sub.Params || base.Params == "" || sub.Params == "" { + return true + } + bParts := strings.Split(base.Params, ",") + sParts := strings.Split(sub.Params, ",") + if len(bParts) != len(sParts) { + return false + } + for i := range bParts { + if bParts[i] == sParts[i] { + continue + } + // Allow single-identifier generic type parameters (e.g. T -> String) in subclasses. + if isGenericTypeParam(bParts[i]) || isGenericTypeParam(sParts[i]) { + continue + } + return false + } + return true +} + +func isGenericTypeParam(name string) bool { + return len(name) == 1 && name[0] >= 'A' && name[0] <= 'Z' +} + +func typeLocation(t *Type, name string) Location { + return Location{ + Path: t.File.Path, Library: t.File.Lib, + Line: int(t.Line), Column: int(t.Col), Name: name, + } +} + +func memberLocation(m *Member) Location { + return Location{ + Path: m.Owner.File.Path, Library: m.Owner.File.Lib, + Line: int(m.Line), Column: int(m.Col), Name: m.Name, + } +} + +func sortLocations(locs []Location) { + sort.Slice(locs, func(i, j int) bool { + if locs[i].Path != locs[j].Path { + return locs[i].Path < locs[j].Path + } + if locs[i].Line != locs[j].Line { + return locs[i].Line < locs[j].Line + } + return locs[i].Column < locs[j].Column + }) +} + +func sortNavTargets(targets []NavTarget) { + sort.Slice(targets, func(i, j int) bool { + if targets[i].Location.Path != targets[j].Location.Path { + return targets[i].Location.Path < targets[j].Location.Path + } + if targets[i].Location.Line != targets[j].Location.Line { + return targets[i].Location.Line < targets[j].Location.Line + } + return targets[i].Location.Column < targets[j].Location.Column + }) +} diff --git a/internal/codenav/implementations_test.go b/internal/codenav/implementations_test.go new file mode 100644 index 0000000..05c4b41 --- /dev/null +++ b/internal/codenav/implementations_test.go @@ -0,0 +1,152 @@ +package codenav + +import ( + "bytes" + "strings" + "testing" +) + +func buildNavIndex(files map[string]string) *Index { + ix := NewIndex() + for p, src := range files { + ix.Put(ParseFile(p, []byte(src))) + } + return ix +} + +func indexOf(src, needle string) int { + i := strings.Index(src, needle) + if i < 0 { + panic("missing needle: " + needle) + } + return i +} + +func TestImplementationsAndSuperDeclarationsAcrossHierarchy(t *testing.T) { + greeterSrc := `package demo; + +public interface Greeter { + String greet(String name); + String greet(int times); + private void secret() {} + static void helper() {} +} +` + baseSrc := `package demo; + +public abstract class BaseGreeter implements Greeter { + public String greet(String name) { return "Hi " + name; } + public String greet(int times) { return "x"; } +} +` + customSrc := `package demo; + +public class CustomGreeter extends BaseGreeter { + public String greet(String name) { return "Custom " + name; } +} +` + finalSrc := `package demo; + +public final class ClosedGreeter extends CustomGreeter { + public String greet(String name) { return "Final"; } +} +` + callerSrc := `package demo; + +class Caller { + void run(Greeter g) { + g.greet("world"); + } +} +` + ix := buildNavIndex(map[string]string{ + "demo/Greeter.java": greeterSrc, + "demo/BaseGreeter.java": baseSrc, + "demo/CustomGreeter.java": customSrc, + "demo/ClosedGreeter.java": finalSrc, + "demo/Caller.java": callerSrc, + }) + + // 1. Type implementations from Greeter include direct + transitive subclasses. + impls := ix.Implementations("demo/Greeter.java", []byte(greeterSrc), indexOf(greeterSrc, "Greeter {")) + if len(impls) != 3 { + t.Fatalf("Greeter implementations = %+v, want 3 subtypes", impls) + } + + // 2. Method implementations on greet(String) differentiate overload greet(int). + methodImpls := ix.Implementations("demo/Greeter.java", []byte(greeterSrc), indexOf(greeterSrc, "greet(String name)")) + if len(methodImpls) != 3 { + t.Fatalf("greet(String) implementations = %+v, want 3 overrides", methodImpls) + } + intImpls := ix.Implementations("demo/Greeter.java", []byte(greeterSrc), indexOf(greeterSrc, "greet(int times)")) + if len(intImpls) != 1 || intImpls[0].Path != "demo/BaseGreeter.java" { + t.Fatalf("greet(int) implementations = %+v, want only BaseGreeter", intImpls) + } + + // 3. Call-site implementation jump works directly without landing on declaration first. + callImpls := ix.Implementations("demo/Caller.java", []byte(callerSrc), indexOf(callerSrc, `greet("world")`)) + if len(callImpls) != 3 { + t.Fatalf("call-site greet implementations = %+v, want 3 overrides", callImpls) + } + + // 4. Final class has zero implementations; private/static interface methods have zero implementations. + closedImpls := ix.Implementations("demo/ClosedGreeter.java", []byte(finalSrc), indexOf(finalSrc, "ClosedGreeter")) + if len(closedImpls) != 0 { + t.Fatalf("final class implementations = %+v, want 0", closedImpls) + } + if got := ix.Implementations("demo/Greeter.java", []byte(greeterSrc), indexOf(greeterSrc, "secret()")); len(got) != 0 { + t.Fatalf("private method implementations = %+v, want 0", got) + } + if got := ix.Implementations("demo/Greeter.java", []byte(greeterSrc), indexOf(greeterSrc, "helper()")); len(got) != 0 { + t.Fatalf("static method implementations = %+v, want 0", got) + } + + // 5. Super declarations from ClosedGreeter.greet(String) find CustomGreeter, BaseGreeter, and Greeter. + supers := ix.SuperDeclarations("demo/ClosedGreeter.java", []byte(finalSrc), indexOf(finalSrc, "greet(String name)")) + if len(supers) != 3 { + t.Fatalf("ClosedGreeter.greet supers = %+v, want 3 ancestors", supers) + } + + // 6. Type super declarations from CustomGreeter find BaseGreeter. + typeSupers := ix.SuperDeclarations("demo/CustomGreeter.java", []byte(customSrc), indexOf(customSrc, "CustomGreeter")) + if len(typeSupers) != 1 || typeSupers[0].Path != "demo/BaseGreeter.java" { + t.Fatalf("CustomGreeter supers = %+v, want BaseGreeter", typeSupers) + } + + // 7. Navigation markers on intermediate CustomGreeter emit BOTH up and down icons. + markers := ix.NavigationMarkers("demo/CustomGreeter.java", []byte(customSrc)) + if len(markers) != 4 { + t.Fatalf("CustomGreeter markers = %+v, want 4 (class up/down + greet up/down)", markers) + } + // CustomGreeter implements Greeter indirectly, so method up prefers "interface" because ancestor is Greeter. + for _, m := range markers { + if m.Line == 3 && m.Direction == "up" && m.Relation != "interface" { + t.Errorf("CustomGreeter.greet up relation = %q, want interface", m.Relation) + } + if m.Line == 2 && m.Direction == "up" && m.Relation != "inheritance" { + t.Errorf("CustomGreeter class up relation = %q, want inheritance", m.Relation) + } + } +} + +func TestCyclicInheritanceGuardDoesNotLoop(t *testing.T) { + aSrc := "package cyc; class A extends B { void m() {} }\n" + bSrc := "package cyc; class B extends A { void m() {} }\n" + ix := buildNavIndex(map[string]string{ + "cyc/A.java": aSrc, + "cyc/B.java": bSrc, + }) + + impls := ix.Implementations("cyc/A.java", []byte(aSrc), bytes.Index([]byte(aSrc), []byte("A extends"))) + if len(impls) != 1 || impls[0].Path != "cyc/B.java" { + t.Fatalf("cyclic implementations = %+v, want only B", impls) + } + supers := ix.SuperDeclarations("cyc/A.java", []byte(aSrc), bytes.Index([]byte(aSrc), []byte("m()"))) + if len(supers) != 1 || supers[0].Path != "cyc/B.java" { + t.Fatalf("cyclic supers = %+v, want only B.m", supers) + } + markers := ix.NavigationMarkers("cyc/A.java", []byte(aSrc)) + if len(markers) != 4 { + t.Fatalf("cyclic markers = %+v, want 4", markers) + } +} diff --git a/internal/codenav/parse.go b/internal/codenav/parse.go index 4f44649..b7337ae 100644 --- a/internal/codenav/parse.go +++ b/internal/codenav/parse.go @@ -44,15 +44,19 @@ type File struct { // Type is a class, interface, enum, record or annotation type declaration. // Line and Col locate its name (0-based line, byte column). type Type struct { - Name, FQN string - Kind declKind - File *File - Line, Col int32 - Outer *Type - Supers []string // as written, generics stripped - Members []*Member - Nested []*Type - Lombok uint8 // lombokGetter | lombokSetter + Name, FQN string + Kind declKind + File *File + Line, Col int32 + Outer *Type + Supers []string // as written, generics stripped + Extends []string // types in extends clause, generics stripped + Implements []string // types in implements clause, generics stripped + Final bool + Abstract bool + Members []*Member + Nested []*Type + Lombok uint8 // lombokGetter | lombokSetter // Positions of @Builder and @Slf4j-style annotations (-1 if absent): // Lombok-generated members have no source of their own, so navigation // lands on the annotation, as JDTLS does. @@ -82,6 +86,10 @@ type Member struct { Type string // declared/return type, generics and dims stripped; "" for ctors Arity int16 Varargs bool + Private bool + Static bool + Final bool + Abstract bool Params string // parameters' simple type names, comma-separated (Lithe addition, see overloads.go) Owner *Type Line, Col int32 @@ -229,10 +237,11 @@ func (p *parser) skipAnnotation(i int) (int, string) { } type annos struct { - lombok uint8 - builder, logAt pos - logType string - noArgs, allArgs, reqArgs pos + lombok uint8 + builder, logAt pos + logType string + noArgs, allArgs, reqArgs pos + private, static, final, abstract bool } // lombokLoggers is the logger type each Lombok log annotation generates; @@ -286,6 +295,16 @@ func (p *parser) skipModifiers(i int) (int, annos) { continue } if p.ident(i) && modifiers[p.txt(i)] || p.is(i, "-") && p.is(i-1, "non") { + switch p.txt(i) { + case "private": + an.private = true + case "static": + an.static = true + case "final": + an.final = true + case "abstract": + an.abstract = true + } i++ continue } @@ -478,7 +497,8 @@ func (p *parser) parseBody(i int, owner *Type, enum bool) int { } switch { case p.is(j, "("): - m := &Member{Name: p.in.s([]byte(p.txt(last))), Owner: owner, Line: p.toks[last].Line, Col: p.col(p.toks[last])} + m := &Member{Name: p.in.s([]byte(p.txt(last))), Owner: owner, Line: p.toks[last].Line, Col: p.col(p.toks[last]), + Private: an.private, Static: an.static, Final: an.final, Abstract: an.abstract} if last == typeStart { m.Kind = kCtor } else { @@ -651,7 +671,8 @@ func (p *parser) parseTypeDecl(i int, outer *Type, an annos) int { nameTok := i + 1 t := &Type{Name: p.in.s([]byte(p.txt(nameTok))), File: p.f, Outer: outer, Line: p.toks[nameTok].Line, Col: p.col(p.toks[nameTok]), Lombok: an.lombok, - BuilderAt: an.builder, LogAt: an.logAt, LogType: an.logType, NoArgsAt: an.noArgs, AllArgsAt: an.allArgs, ReqArgsAt: an.reqArgs} + BuilderAt: an.builder, LogAt: an.logAt, LogType: an.logType, NoArgsAt: an.noArgs, AllArgsAt: an.allArgs, ReqArgsAt: an.reqArgs, + Final: an.final || kw == "enum" || kw == "record", Abstract: an.abstract || kw == "interface"} switch kw { case "class": t.Kind = kClass @@ -695,7 +716,14 @@ func (p *parser) parseTypeDecl(i int, outer *Type, an annos) int { for p.ident(j) && p.is(j+1, ".") && p.ident(j+2) { j += 2 } - t.Supers = append(t.Supers, p.typeText(s, j+1)) + name := p.typeText(s, j+1) + t.Supers = append(t.Supers, name) + switch mode { + case "extends": + t.Extends = append(t.Extends, name) + case "implements": + t.Implements = append(t.Implements, name) + } j++ default: j++ diff --git a/internal/lithesdk/lithe/backend.go b/internal/lithesdk/lithe/backend.go new file mode 100644 index 0000000..2710c3c --- /dev/null +++ b/internal/lithesdk/lithe/backend.go @@ -0,0 +1,1236 @@ +package lithe + +import ( + "bufio" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "runtime" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + "unicode/utf8" +) + +// FunctionHandler serves one plugin function. params is the call's params +// object, {} when the host sent none. The result is any JSON-serializable +// value, at most 1 MiB encoded. Return a [*PluginError] to answer with the +// plugin's own code, [ErrCancelled] (or an error wrapping it) when the call +// stopped because it was cancelled; any other error answers as an internal +// failure whose text stays in the backend. +type FunctionHandler func(params json.RawMessage, call *Context) (any, error) + +// ViewHandler serves a view function; see [Backend.View]. +type ViewHandler func(event *ViewEvent, call *Context) (ViewResult, error) + +// KeymapImportHandler serves one shortcut import provider; see +// [Backend.KeymapImportProvider]. +type KeymapImportHandler func(request KeymapImportRequest, call *Context) (any, error) + +// CommandHandler handles a run of one of the plugin's commands, with the +// workspace context it ran in, nil when it has none. +type CommandHandler func(commandID string, context *WorkspaceContext) error + +// NotificationHandler handles a host notification's params. +type NotificationHandler func(params json.RawMessage) error + +// phase: idle -> listening -> initializing -> ready -> shuttingDown -> exited. +type phase int + +const ( + phaseIdle phase = iota + phaseListening + phaseInitializing + phaseReady + phaseShuttingDown + phaseExited +) + +type running struct { + functionID string + cancellation *Cancellation +} + +type state struct { + phase phase + functions map[string]FunctionHandler + keymapProviders map[string]KeymapImportHandler + selectedKeymapProviders []string + logging bool + loggingReady bool + earlyDiagnostics []map[string]any + quietSuccess map[string]bool + // functionsNegotiated is true when the host offered plugin functions, + // version FunctionsVersion. + functionsNegotiated bool + // incoming are the host requests being handled, by JSON-RPC ID. + incoming map[string]*running + // outgoing are the requests this backend sent to the host, by ID. + outgoing map[string]*outgoing + channel channel + // slotSignal is closed, and replaced, when a host-request slot frees or + // a waiting request must look again. + slotSignal chan struct{} +} + +// shared is everything handler goroutines share with the session. Locks are +// taken in the order registrations, capabilitiesMu, mu, outputMu, never the +// other way round. +type shared struct { + name string + mu sync.Mutex + state state + + outputMu sync.Mutex + output *bufio.Writer + + // registrations serializes register and unregister so the host sees + // them in call order. + registrations sync.Mutex + nextRequest atomic.Uint64 + + // capabilities caches the session's getCapabilities answer. + capabilitiesMu sync.Mutex + capabilities any +} + +// notifySlots wakes every request waiting for a slot. The caller holds mu. +func (s *shared) notifySlots() { + close(s.state.slotSignal) + s.state.slotSignal = make(chan struct{}) +} + +func (s *shared) currentPhase() phase { + s.mu.Lock() + defer s.mu.Unlock() + return s.state.phase +} + +func (s *shared) functionsNegotiated() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.state.functionsNegotiated +} + +func (s *shared) runningCancellations() []*Cancellation { + tokens := make([]*Cancellation, 0, len(s.state.incoming)) + for _, call := range s.state.incoming { + tokens = append(tokens, call.cancellation) + } + return tokens +} + +// requireFunctions checks, with mu held, that functions can be registered. +func (s *shared) requireFunctions() error { + switch { + case s.state.phase == phaseExited: + return closedError() + case s.state.phase == phaseReady && s.state.functionsNegotiated: + return nil + default: + return newSdkError("sdk.functions.unavailable", "The host has not negotiated plugin functions.") + } +} + +// write sends one message. After a failed write every later one is +// dropped: the protocol pipe is gone and the host owns the process's end. +func (s *shared) write(message any) { + body, err := encodeJSON(message) + if err != nil { + return + } + s.outputMu.Lock() + defer s.outputMu.Unlock() + if s.output == nil { + return + } + if writeFrame(s.output, body) != nil { + s.output = nil + } +} + +// answer is a JSON-RPC result, or an error object when err is set. +type answer struct { + result any + err map[string]any +} + +func rpcError(code int, message string) answer { + return answer{err: map[string]any{"code": code, "message": message}} +} + +func (s *shared) respond(id any, a answer) { + if a.err != nil { + s.write(map[string]any{"jsonrpc": "2.0", "id": id, "error": a.err}) + return + } + s.write(map[string]any{"jsonrpc": "2.0", "id": id, "result": a.result}) +} + +func (s *shared) failed(operation, code string) { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": map[string]any{ + "kind": "operationFailed", "operation": operation, "code": code, "durationMs": 0, + }}) +} + +func (s *shared) finish(code int) int { + s.mu.Lock() + s.state.phase = phaseExited + s.closeChannel() + tokens := s.runningCancellations() + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + s.outputMu.Lock() + s.output = nil + s.outputMu.Unlock() + return code +} + +// notifyHandler runs a notification handler off the reading goroutine; a +// failure is logged with its category only. +func (s *shared) notifyHandler(handler func() error) { + go func() { + defer func() { + if recover() != nil { + s.failed("notification", "panic") + } + }() + if err := handler(); err != nil { + if kind, _ := classify(err); kind != kindCancelled { + s.failed("notification", failureKind(err)) + } + } + }() +} + +// request sends a lithe/function/* request; it takes no host-request slot. +func (s *shared) request(method string, params any) (any, error) { + return s.exchange(method, params, false, nil, nil) +} + +// Backend is a plugin backend. Declare functions and hooks, then call +// [Backend.Listen]: +// +// backend := lithe.NewBackend("example-backend").Version("1.0.0") +// err := backend.Function("snapshot.refresh", func(params json.RawMessage, call *lithe.Context) (any, error) { +// call.ProgressPercent("Refreshing", 10) +// var request struct{ Name *string } +// if json.Unmarshal(params, &request) != nil || request.Name == nil { +// return nil, lithe.NewPluginError("example.invalidName", `"name" must be a string.`) +// } +// return map[string]any{"refreshed": *request.Name}, nil +// }) +// if err != nil { +// log.Fatal(err) +// } +// os.Exit(backend.Listen()) +// +// Declare everything before Listen; a Backend is not safe for concurrent +// declaration. After that, use [Backend.Handle] from any goroutine. +type Backend struct { + shared *shared + version string + hasVersion bool + initializeHooks []func(*Initialize) error + shutdownHooks []func() + commands map[string]CommandHandler + contextsChanged NotificationHandler + hostNotifications map[string]NotificationHandler +} + +// NewBackend returns a backend; name is reported as serverInfo.name. +func NewBackend(name string) *Backend { + s := &shared{name: name} + s.state = state{ + phase: phaseIdle, + functions: map[string]FunctionHandler{}, + keymapProviders: map[string]KeymapImportHandler{}, + quietSuccess: map[string]bool{}, + incoming: map[string]*running{}, + outgoing: map[string]*outgoing{}, + channel: channel{routes: map[string]*route{}}, + slotSignal: make(chan struct{}), + } + return &Backend{ + shared: s, + commands: map[string]CommandHandler{}, + hostNotifications: map[string]NotificationHandler{}, + } +} + +// Version sets serverInfo.version. +func (b *Backend) Version(version string) *Backend { + b.version, b.hasVersion = version, true + return b +} + +// SuppressSuccessDiagnostics omits the successful terminal diagnostics of a +// registered high-frequency operation; failures stay visible. +func (b *Backend) SuppressSuccessDiagnostics(operation string) error { + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if _, registered := s.state.functions[operation]; !registered && !slices.Contains(operations, operation) { + return newSdkError("sdk.logging.invalidOperation", "Suppress a registered operation.") + } + s.state.quietSuccess[operation] = true + return nil +} + +// Function declares a function offered from the start, in the initialize +// answer. To add one later, use [BackendHandle.RegisterFunction]. +// +// Each call runs on a goroutine of its own, so a handler may block; it +// should stop early when its [Context.Cancellation] fires. +func (b *Backend) Function(id string, handler FunctionHandler) error { + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if err := checkNewFunction(id, s.state.functions); err != nil { + return err + } + s.state.functions[id] = handler + return nil +} + +// View declares the view function a tool window or settings region names in +// view.function: a plugin function whose params the SDK reads into a +// [ViewEvent] and whose [ViewResult] it answers. Params that are not a view +// event fail the call before the handler runs. +func (b *Backend) View(id string, handler ViewHandler) error { + return b.Function(id, func(params json.RawMessage, call *Context) (any, error) { + event, err := ParseViewEvent(params) + if err != nil { + return nil, err + } + result, err := handler(event, call) + if err != nil { + return nil, err + } + return result, nil + }) +} + +// KeymapImportProvider declares a shortcut import provider: id is 1-64 +// lowercase letters, digits or "-", starting with a letter; a backend has at +// most 8. The handler receives an opaque snapshot, never a filesystem path; +// it lists and reads the selected inputs through its call's host. +func (b *Backend) KeymapImportProvider(id string, handler KeymapImportHandler) error { + if !validKeymapProviderID(id) { + return newSdkError("sdk.keymap.invalidID", "Invalid shortcut import provider ID.") + } + s := b.shared + s.mu.Lock() + defer s.mu.Unlock() + if _, exists := s.state.keymapProviders[id]; exists || len(s.state.keymapProviders) >= 8 { + return newSdkError("sdk.keymap.invalidRegistration", "Duplicate provider or provider limit exceeded.") + } + s.state.keymapProviders[id] = handler + return nil +} + +// OnInitialize runs hook before the initialize answer. A hook may read the +// host's params and add functions; an error refuses initialize, mapped like +// a handler's. +func (b *Backend) OnInitialize(hook func(*Initialize) error) { + b.initializeHooks = append(b.initializeHooks, hook) +} + +// OnShutdown runs hook on shutdown, after running calls were cancelled. +func (b *Backend) OnShutdown(hook func()) { + b.shutdownHooks = append(b.shutdownHooks, hook) +} + +// OnCommand handles lithe/host/commands/didRun for one of the plugin's +// commands, its ID from the manifest (1-128 of [a-z0-9.-]). It is an event: +// the host waits for no result, and a failure is only logged. Each run has +// a goroutine of its own. A later handler for the same ID replaces the +// earlier one. +func (b *Backend) OnCommand(commandID string, handler CommandHandler) error { + if !IsCommandID(commandID) { + return newSdkError("sdk.command.invalidID", fmt.Sprintf("Command ID %q must be 1-128 of [a-z0-9.-].", commandID)) + } + b.commands[commandID] = handler + return nil +} + +// OnContextsChanged handles lithe/host/workspace/didChangeContexts with +// { revision }; call Host().Workspace().ListContexts() for the contexts. +func (b *Backend) OnContextsChanged(handler NotificationHandler) { + b.contextsChanged = handler +} + +// OnHostNotification handles a lithe/host/* notification a later host adds. +// Commands, context changes and subscription events have their own APIs. +func (b *Backend) OnHostNotification(method string, handler NotificationHandler) error { + if !strings.HasPrefix(method, hostPrefix) { + return newSdkError("sdk.method.invalid", method+" is not a host notification.") + } + if method == methodContexts || method == methodNotify || method == methodCommandRan { + return newSdkError("sdk.method.reserved", method+" is routed by the SDK; use OnCommand, OnContextsChanged, or Host.Subscribe.") + } + b.hostNotifications[method] = handler + return nil +} + +// Handle returns a handle for other goroutines: runtime registration, host +// services and diagnostics. +func (b *Backend) Handle() *BackendHandle { + return &BackendHandle{shared: b.shared} +} + +// Listen serves the host on stdin and stdout until it sends exit or closes +// stdin, and returns the process exit code. Stdout carries only protocol +// frames: on Unix the SDK moves the protocol to a duplicate of the stdout +// descriptor and points stdout at stderr, so a stray fmt.Println, in the +// plugin or a dependency, lands in the host's log instead of corrupting the +// stream. On Windows plugin code must not write to stdout. +func (b *Backend) Listen() int { + return b.Serve(os.Stdin, protocolOutput()) +} + +// Serve serves the host on the given streams; [Backend.Listen] uses stdin +// and stdout. +func (b *Backend) Serve(input io.Reader, output io.Writer) int { + s := b.shared + s.mu.Lock() + s.state.phase = phaseListening + s.mu.Unlock() + s.outputMu.Lock() + s.output = bufio.NewWriter(output) + s.outputMu.Unlock() + reader := bufio.NewReader(input) + for { + message, err := readFrame(reader) + switch { + case err != nil: + b.Handle().Diagnostics().terminal("notification", errors.New("framing_error"), time.Now()) + return s.finish(1) + case message == nil: + code := 0 + if s.currentPhase() != phaseShuttingDown { + code = 1 + } + return s.finish(code) + case message.malformed: + s.respond(nil, rpcError(rpcParseError, "The message is not valid JSON.")) + default: + if code, exit := b.dispatch(message.value); exit { + return s.finish(code) + } + } + } +} + +// dispatch handles one message; it reports the exit code once the host +// sent exit. +func (b *Backend) dispatch(message any) (int, bool) { + s := b.shared + object, ok := message.(map[string]any) + if !ok { + // Valid JSON that is not a message object, such as null or a batch. + s.respond(nil, rpcError(rpcInvalidRequest, "The message is not a JSON-RPC object.")) + return 0, false + } + id := object["id"] + params := object["params"] + method, isMethod := object["method"].(string) + switch { + case !isMethod && id != nil: + s.settleOutgoing(id, object) + case !isMethod: + case id != nil: + b.handleRequest(id, method, params) + default: + return b.handleNotification(method, params) + } + return 0, false +} + +func (b *Backend) handleRequest(id any, method string, params any) { + s := b.shared + switch method { + case methodInitialize: + b.initialize(id, params) + return + case methodShutdown: + b.shutdown(id) + return + } + switch s.currentPhase() { + case phaseReady: + switch method { + case methodInvoke: + s.invoke(id, params) + case methodKeymapImport: + s.invokeKeymap(id, params) + default: + s.respond(id, rpcError(rpcMethodNotFound, "Unsupported method: "+method)) + } + case phaseIdle, phaseListening, phaseInitializing: + s.respond(id, rpcError(rpcServerNotInitialized, "The backend is not initialized.")) + default: + s.respond(id, rpcError(rpcInvalidRequest, "The backend is shutting down.")) + } +} + +func (b *Backend) handleNotification(method string, params any) (int, bool) { + s := b.shared + switch { + case method == methodExit: + if s.currentPhase() != phaseShuttingDown { + return 1, true + } + return 0, true + case method == methodCancelRequest: + key := requestKey(field(params, "id")) + s.mu.Lock() + call := s.state.incoming[key] + s.mu.Unlock() + if call != nil { + call.cancellation.Cancel() + } + case strings.HasPrefix(method, hostPrefix): + b.hostNotification(method, params) + } + // initialized and anything else a plugin backend is not sent. + return 0, false +} + +// hostNotification routes a host notification. Core checked its shape and +// the session's grant; one this SDK does not know is ignored, as the +// contract asks. +func (b *Backend) hostNotification(method string, params any) { + s := b.shared + object, ok := params.(map[string]any) + if !s.functionsNegotiated() || !ok { + return + } + switch method { + case methodNotify: + s.deliver(object) + case methodCommandRan: + commandID, _ := object["commandID"].(string) + handler := b.commands[commandID] + if handler == nil { + s.failed("notification", "command_unhandled") + return + } + context := workspaceContextFromReference(object["context"]) + s.notifyHandler(func() error { return handler(commandID, context) }) + default: + handler := b.hostNotifications[method] + if method == methodContexts { + handler = b.contextsChanged + } + if handler != nil { + data := raw(params) + s.notifyHandler(func() error { return handler(data) }) + } + } +} + +// runHook runs one initialize hook; it reports the error answer when the +// hook refused or panicked. +func runHook(hook func(*Initialize) error, initialize *Initialize) (refusal map[string]any) { + defer func() { + if recover() != nil { + refusal = internalResponse() + } + }() + if err := hook(initialize); err != nil { + return responseError(err) + } + return nil +} + +func (b *Backend) initialize(id, params any) { + s := b.shared + s.mu.Lock() + if s.state.phase != phaseListening { + s.mu.Unlock() + s.respond(id, rpcError(rpcInvalidRequest, "initialize was already received.")) + return + } + s.state.phase = phaseInitializing + s.mu.Unlock() + + experimentalOffer := pointer(params, "capabilities", "experimental") + keymapOffer, hasKeymapOffer := field(experimentalOffer, "litheKeymapImport"), false + if object, ok := experimentalOffer.(map[string]any); ok { + _, hasKeymapOffer = object["litheKeymapImport"] + } + logging := offers(field(experimentalOffer, "litheLogging"), LoggingVersion) + s.mu.Lock() + s.state.logging = logging + s.state.loggingReady = false + s.state.earlyDiagnostics = nil + if !logging { + s.state.phase = phaseListening + } + existing := sortedKeys(s.state.functions) + s.mu.Unlock() + if !logging { + s.respond(id, rpcError(rpcInvalidRequest, fmt.Sprintf("The backend requires litheLogging version %d.", LoggingVersion))) + return + } + functions := offers(field(experimentalOffer, "litheFunctions"), FunctionsVersion) + init := &Initialize{params: params, functions: functions, existing: existing, added: map[string]FunctionHandler{}} + for _, hook := range b.initializeHooks { + if refusal := runHook(hook, init); refusal != nil { + s.mu.Lock() + s.state.phase = phaseListening + s.mu.Unlock() + s.respond(id, answer{err: refusal}) + return + } + } + + // The state stays locked until the answer is written, so a function + // registered from another goroutine cannot overtake it. + s.mu.Lock() + for functionID, handler := range init.added { + s.state.functions[functionID] = handler + } + s.state.functionsNegotiated = functions + experimental := map[string]any{"litheLogging": map[string]any{"version": LoggingVersion}} + if hasKeymapOffer && offers(keymapOffer, KeymapImportVersion) { + if providers, ok := field(keymapOffer, "providers").([]any); ok && len(providers) <= 8 { + var selected []string + for _, value := range providers { + providerID, ok := value.(string) + if _, registered := s.state.keymapProviders[providerID]; ok && registered && !slices.Contains(selected, providerID) { + selected = append(selected, providerID) + } + } + slices.Sort(selected) + s.state.selectedKeymapProviders = selected + if len(selected) > 0 { + experimental["litheKeymapImport"] = map[string]any{"version": KeymapImportVersion, "providers": selected} + } + } + } + if functions { + declared := []any{} + for _, functionID := range sortedKeys(s.state.functions) { + declared = append(declared, map[string]any{"id": functionID}) + } + experimental["litheFunctions"] = map[string]any{"version": FunctionsVersion, "functions": declared} + } + serverInfo := map[string]any{"name": s.name} + if b.hasVersion { + serverInfo["version"] = b.version + } + s.state.phase = phaseReady + s.respond(id, answer{result: map[string]any{ + "capabilities": map[string]any{"experimental": experimental}, + "serverInfo": serverInfo, + }}) + s.state.loggingReady = true + early := s.state.earlyDiagnostics + s.state.earlyDiagnostics = nil + s.mu.Unlock() + for _, params := range early { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": params}) + } +} + +func (b *Backend) shutdown(id any) { + s := b.shared + s.mu.Lock() + switch s.state.phase { + case phaseListening, phaseInitializing, phaseReady: + default: + s.mu.Unlock() + s.respond(id, rpcError(rpcInvalidRequest, "shutdown was already received.")) + return + } + s.state.phase = phaseShuttingDown + tokens := s.runningCancellations() + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + for _, hook := range b.shutdownHooks { + func() { + defer func() { + if recover() != nil { + s.failed("shutdown", "panic") + } + }() + hook() + }() + } + s.respond(id, answer{result: nil}) +} + +// outcome is how a handler ended. +type outcome struct { + result any + err error + panicked bool +} + +func runCall(handler func() (any, error)) (ended outcome) { + defer func() { + if recover() != nil { + ended = outcome{panicked: true} + } + }() + result, err := handler() + return outcome{result: result, err: err} +} + +func (s *shared) invoke(id, params any) { + functionID, _ := field(params, "functionID").(string) + operationID := field(params, "operationID") + // What nested cross-plugin calls name as the call they belong to. + parent, _ := operationID.(string) + if !isParentOperationID(parent) { + parent = "" + } + callParams := field(params, "params") + if callParams == nil { + callParams = map[string]any{} + } + key := requestKey(id) + cancellation := NewCancellation() + var ( + handler FunctionHandler + workspaceContext *WorkspaceContext + caller *Caller + ) + s.mu.Lock() + if s.state.functionsNegotiated { + workspaceContext = workspaceContextFromReference(field(params, "context")) + caller = callerFromValue(field(params, "caller")) + handler = s.state.functions[functionID] + } + if handler != nil { + s.state.incoming[key] = &running{functionID: functionID, cancellation: cancellation} + } + s.mu.Unlock() + if handler == nil { + s.respond(id, rpcError(rpcInvalidParams, fmt.Sprintf("Function %s is not registered.", functionID))) + return + } + go func() { + // Ends host requests the call left behind, on copies of its host. + ended := NewCancellation() + call := &Context{ + shared: s, + functionID: functionID, + operationID: operationID, + diagnosticOperationID: requestOperationID(operationID, id), + cancellation: cancellation, + host: &Host{shared: s, scope: []*Cancellation{cancellation, ended}, parentOperation: parent}, + workspaceContext: workspaceContext, + caller: caller, + } + call.reporting.Store(true) + started := time.Now() + data := raw(callParams) + result := runCall(func() (any, error) { return handler(data, call) }) + call.reporting.Store(false) + ended.Cancel() + a := s.functionAnswer(call, functionID, result, started) + s.mu.Lock() + delete(s.state.incoming, key) + s.mu.Unlock() + s.respond(id, a) + }() +} + +func (s *shared) invokeKeymap(id, params any) { + object, isObject := params.(map[string]any) + provider, _ := object["providerID"].(string) + snapshot, _ := object["snapshotID"].(string) + if !isObject || len(object) != 2 || !validKeymapProviderID(provider) || !validSnapshotID(snapshot) { + s.respond(id, rpcError(rpcInvalidParams, "Invalid shortcut import request.")) + return + } + callID := "keymap:" + provider + key := requestKey(id) + cancellation := NewCancellation() + var handler KeymapImportHandler + s.mu.Lock() + if slices.Contains(s.state.selectedKeymapProviders, provider) { + handler = s.state.keymapProviders[provider] + } + if handler != nil { + s.state.incoming[key] = &running{functionID: callID, cancellation: cancellation} + } + s.mu.Unlock() + if handler == nil { + s.respond(id, rpcError(rpcInvalidParams, "Shortcut import provider was not negotiated.")) + return + } + go func() { + ended := NewCancellation() + call := &Context{ + shared: s, + functionID: callID, + diagnosticOperationID: requestOperationID(nil, id), + cancellation: cancellation, + host: &Host{shared: s, scope: []*Cancellation{cancellation, ended}}, + } + started := time.Now() + request := KeymapImportRequest{providerID: provider, snapshotID: snapshot} + result := runCall(func() (any, error) { return handler(request, call) }) + ended.Cancel() + // Facts name the wire method Core registered, not the per-provider call ID. + a := s.functionAnswer(call, methodKeymapImport, result, started) + s.mu.Lock() + delete(s.state.incoming, key) + s.mu.Unlock() + s.respond(id, a) + }() +} + +// functionAnswer is the answer to one call. A cancelled call answers as +// cancelled whatever the handler returned, and failures the host never sees +// in full are logged with a fixed category, without their private contents. +func (s *shared) functionAnswer(call *Context, function string, ended outcome, started time.Time) answer { + diagnostics := call.Diagnostics() + switch { + case call.cancellation.IsCancelled(): + return answer{err: cancelledResponse()} + case ended.panicked: + code, duration := "panic", elapsed(started) + _ = diagnostics.record("operationFailed", function, &code, nil, &duration) + return answer{err: internalResponse()} + case ended.err != nil: + if kind, _ := classify(ended.err); kind != kindCancelled { + diagnostics.terminal(function, ended.err, started) + } + return answer{err: responseError(ended.err)} + } + body, err := encodeJSON(ended.result) + if err != nil || len(body) > maxResultBytes { + diagnostics.terminal(function, errors.New("result_limit"), started) + return answer{err: internalResponse()} + } + quiet := call.quietSuccess.Load() + if !quiet { + s.mu.Lock() + quiet = s.state.quietSuccess[function] + s.mu.Unlock() + } + if !quiet { + diagnostics.terminal(function, nil, started) + } + return answer{result: json.RawMessage(body)} +} + +func checkNewFunction(id string, functions map[string]FunctionHandler) error { + if !IsFunctionID(id) { + return newSdkError("sdk.function.invalidID", fmt.Sprintf("Function ID %q must be dot-separated lowerCamelCase segments of at most 128 bytes.", id)) + } + if _, exists := functions[id]; exists { + return newSdkError("sdk.function.duplicate", fmt.Sprintf("Function %s is already declared.", id)) + } + if len(functions) >= MaxFunctions { + return newSdkError("sdk.function.limit", fmt.Sprintf("A backend serves at most %d functions.", MaxFunctions)) + } + return nil +} + +func sortedKeys[V any](values map[string]V) []string { + keys := make([]string, 0, len(values)) + for key := range values { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} + +// Initialize is what a hook sees of initialize, before the backend answers +// it. +type Initialize struct { + params any + functions bool + existing []string + added map[string]FunctionHandler +} + +// Params are the host's initialize params. +func (i *Initialize) Params() json.RawMessage { return raw(i.params) } + +// FunctionsVersion is the plugin-function protocol version the backend will +// answer, with false when the host did not offer it. +func (i *Initialize) FunctionsVersion() (uint64, bool) { + return FunctionsVersion, i.functions +} + +// RootPath is the rootUri as a path. For a plugin backend this is the +// plugin's ${stateDir}, also the working directory. +func (i *Initialize) RootPath() (string, bool) { + uri, ok := field(i.params, "rootUri").(string) + if !ok { + return "", false + } + return fileURIPath(uri) +} + +// Function adds a function to the initial list, for example one that +// depends on state found at startup. +func (i *Initialize) Function(id string, handler FunctionHandler) error { + if slices.Contains(i.existing, id) { + return newSdkError("sdk.function.duplicate", fmt.Sprintf("Function %s is already declared.", id)) + } + if len(i.existing)+len(i.added) >= MaxFunctions { + return newSdkError("sdk.function.limit", fmt.Sprintf("A backend serves at most %d functions.", MaxFunctions)) + } + if err := checkNewFunction(id, i.added); err != nil { + return err + } + i.added[id] = handler + return nil +} + +// fileURIPath is the path of a file: URI, percent-decoded. +func fileURIPath(uri string) (string, bool) { + rest, ok := strings.CutPrefix(uri, "file://") + if !ok { + return "", false + } + path := strings.TrimPrefix(rest, "localhost") + if !strings.HasPrefix(path, "/") { + return "", false + } + decoded := make([]byte, 0, len(path)) + for index := 0; index < len(path); { + if path[index] == '%' && index+2 < len(path) { + value, err := strconv.ParseUint(path[index+1:index+3], 16, 8) + if err != nil { + return "", false + } + decoded = append(decoded, byte(value)) + index += 3 + continue + } + decoded = append(decoded, path[index]) + index++ + } + if !utf8.Valid(decoded) { + return "", false + } + result := string(decoded) + // /C:/Users on Windows. + if runtime.GOOS == "windows" && len(result) > 2 && result[2] == ':' { + result = result[1:] + } + for len(result) > 1 && strings.HasSuffix(result, "/") { + result = result[:len(result)-1] + } + return result, true +} + +// Context is one running function call. +type Context struct { + shared *shared + functionID string + operationID any + diagnosticOperationID string + cancellation *Cancellation + host *Host + workspaceContext *WorkspaceContext + caller *Caller + reporting atomic.Bool + quietSuccess atomic.Bool +} + +// SuppressSuccessDiagnostics omits only this call's successful terminal +// fact; failures remain visible. +func (c *Context) SuppressSuccessDiagnostics() { c.quietSuccess.Store(true) } + +// Diagnostics records structured facts correlated with the host's original +// operation ID. +func (c *Context) Diagnostics() *Diagnostics { + return &Diagnostics{shared: c.shared, operationID: c.diagnosticOperationID} +} + +// FunctionID is the ID of the function being called. +func (c *Context) FunctionID() string { return c.functionID } + +// Cancellation fires when the host cancels the call, withdraws its +// function, or shuts the backend down. Core has already ended the call by +// then, so a handler should stop its work and return promptly. +func (c *Context) Cancellation() *Cancellation { return c.cancellation } + +// CheckCancelled returns ErrCancelled once the call is cancelled. +func (c *Context) CheckCancelled() error { return c.cancellation.Check() } + +// Progress reports progress of this call; the host shows the latest report. +// message is cut to 1024 bytes. Reports after the call ended are dropped. +func (c *Context) Progress(message string) { c.progress(message, nil) } + +// ProgressPercent reports progress with a percentage, clamped to 0-100. +func (c *Context) ProgressPercent(message string, percentage int) { + percentage = max(0, min(percentage, 100)) + c.progress(message, &percentage) +} + +func (c *Context) progress(message string, percentage *int) { + if !c.reporting.Load() { + return + } + report := map[string]any{ + "operationID": c.operationID, + "message": boundedText(message, maxErrorMessageBytes), + } + if percentage != nil { + report["percentage"] = *percentage + } + c.shared.write(map[string]any{"jsonrpc": "2.0", "method": methodProgress, "params": report}) +} + +// Host is the host services of this call. A request still waiting for the +// host when the call is cancelled or ends fails with sdk.call.cancelled, +// which counts as a cancelled answer when returned; the SDK also cancels it +// on the wire. +func (c *Context) Host() *Host { return c.host } + +// WorkspaceContext is the { contextID, generation } of the window the call +// came from; nil for calls from no workspace, such as a view or page shown +// without one. +func (c *Context) WorkspaceContext() *WorkspaceContext { return c.workspaceContext } + +// Caller is the plugin that called this function through Core's relay; nil +// when the host started the call, and for a caller of any other shape. +func (c *Context) Caller() *Caller { return c.caller } + +// Credentials is Host().Credentials(). +func (c *Context) Credentials() *Credentials { return c.host.Credentials() } + +// Backend is a handle to the backend serving the call. +func (c *Context) Backend() *BackendHandle { return &BackendHandle{shared: c.shared} } + +// Caller is the plugin that called a function through Core's relay. Core +// writes it from the identity of the calling session and a caller cannot +// supply it, so a provider may key per-caller state by it. +type Caller struct { + pluginID string +} + +// callerFromValue reads the caller of a relayed call, which is exactly +// { pluginID } with a non-empty string. +func callerFromValue(value any) *Caller { + object, ok := value.(map[string]any) + if !ok || len(object) != 1 { + return nil + } + pluginID, ok := object["pluginID"].(string) + if !ok || pluginID == "" { + return nil + } + return &Caller{pluginID: pluginID} +} + +// PluginID is the calling plugin's ID, such as dev.lithe.fixture.python. +func (c *Caller) PluginID() string { return c.pluginID } + +// KeymapImportRequest is a single host-authorized source snapshot for a +// shortcut import. +type KeymapImportRequest struct { + providerID string + snapshotID string +} + +// KeymapSourceFile is a source file in the host's selected, read-only +// snapshot. Path is relative to the selected source and only a label, never +// authority. +type KeymapSourceFile struct { + ID string + Path string + ByteCount uint64 +} + +// ProviderID is the provider the host called. +func (r KeymapImportRequest) ProviderID() string { return r.providerID } + +// SnapshotID names the snapshot the host captured. +func (r KeymapImportRequest) SnapshotID() string { return r.snapshotID } + +// ListInputs lists the declared files captured for this request. +func (r KeymapImportRequest) ListInputs(host *Host) ([]KeymapSourceFile, error) { + result, err := host.request(methodKeymapInputs, map[string]any{"providerID": r.providerID, "snapshotID": r.snapshotID}) + if err != nil { + return nil, err + } + invalid := newSdkError("sdk.keymap.invalidResponse", "Invalid shortcut source list.") + entries, ok := field(result, "files").([]any) + if !ok || len(entries) > 128 { + return nil, invalid + } + files := make([]KeymapSourceFile, 0, len(entries)) + for _, entry := range entries { + id, ok := field(entry, "id").(string) + if !ok || !validSnapshotID(id) { + return nil, invalid + } + path, ok := field(entry, "path").(string) + if !ok || path == "" || len(path) > 4096 { + return nil, invalid + } + size, ok := unsignedInteger(field(entry, "byteCount")) + if !ok || size > 1_048_576 { + return nil, invalid + } + files = append(files, KeymapSourceFile{ID: id, Path: path, ByteCount: size}) + } + return files, nil +} + +// ReadChunk reads one bounded chunk, at most maximumBytes (1-131072) from +// offset (at most 1 MiB), of a file ID ListInputs returned. +func (r KeymapImportRequest) ReadChunk(host *Host, fileID string, offset uint64, maximumBytes uint32) ([]byte, error) { + invalid := newSdkError("sdk.keymap.invalidChunk", "Invalid shortcut source chunk.") + if !validSnapshotID(fileID) || offset > 1_048_576 || maximumBytes == 0 || maximumBytes > 131_072 { + return nil, invalid + } + result, err := host.request(methodKeymapChunk, map[string]any{ + "providerID": r.providerID, "snapshotID": r.snapshotID, + "fileID": fileID, "offset": offset, "maximumBytes": maximumBytes, + }) + if err != nil { + return nil, err + } + encoded, ok := field(result, "data").(string) + // Standard base64 with padding and nothing else; the decoder would skip + // line breaks. + if !ok || len(encoded) > 174_764 || strings.ContainsAny(encoded, "\r\n") { + return nil, invalid + } + data, err := base64.StdEncoding.Strict().DecodeString(encoded) + if err != nil || len(data) > int(maximumBytes) { + return nil, invalid + } + return data, nil +} + +func validKeymapProviderID(id string) bool { + if id == "" || len(id) > 64 || id[0] < 'a' || id[0] > 'z' { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '-' { + return false + } + } + return true +} + +func validSnapshotID(id string) bool { + if id == "" || len(id) > 128 { + return false + } + for i := 0; i < len(id); i++ { + if !isASCIIAlnum(id[i]) && id[i] != '-' && id[i] != '_' { + return false + } + } + return true +} + +// BackendHandle is a handle to a backend for any goroutine. +type BackendHandle struct { + shared *shared +} + +// Diagnostics records structured facts outside a call; no operation ID is +// fabricated. +func (h *BackendHandle) Diagnostics() *Diagnostics { return &Diagnostics{shared: h.shared} } + +// FunctionsVersion is the negotiated plugin-function protocol version, with +// false before initialize or when the host did not offer it. +func (h *BackendHandle) FunctionsVersion() (uint64, bool) { + return FunctionsVersion, h.shared.functionsNegotiated() +} + +// FunctionIDs are the IDs of the functions the backend currently serves, +// sorted. +func (h *BackendHandle) FunctionIDs() []string { + h.shared.mu.Lock() + defer h.shared.mu.Unlock() + return sortedKeys(h.shared.state.functions) +} + +// RegisterFunction adds a function after initialize and waits until the +// host accepted it. The handler is installed first, because the host may +// invoke it as soon as its registry changed. +func (h *BackendHandle) RegisterFunction(id string, handler FunctionHandler) error { + s := h.shared + s.registrations.Lock() + defer s.registrations.Unlock() + s.mu.Lock() + err := s.requireFunctions() + if err == nil { + err = checkNewFunction(id, s.state.functions) + } + if err != nil { + s.mu.Unlock() + return err + } + s.state.functions[id] = handler + s.mu.Unlock() + if _, err := s.request(methodRegister, map[string]any{"functions": []any{map[string]any{"id": id}}}); err != nil { + s.mu.Lock() + delete(s.state.functions, id) + s.mu.Unlock() + return err + } + return nil +} + +// UnregisterFunction withdraws a function and waits until the host accepted +// it. The host ends the function's running calls as revoked, and the SDK +// cancels them. A handler must not withdraw its own function: that revokes +// the call it runs in. +func (h *BackendHandle) UnregisterFunction(id string) error { + s := h.shared + s.registrations.Lock() + defer s.registrations.Unlock() + s.mu.Lock() + err := s.requireFunctions() + if _, registered := s.state.functions[id]; err == nil && !registered { + err = newSdkError("sdk.function.unknown", fmt.Sprintf("Function %s is not registered.", id)) + } + s.mu.Unlock() + if err != nil { + return err + } + if _, err := s.request(methodUnregister, map[string]any{"ids": []any{id}}); err != nil { + return err + } + s.mu.Lock() + delete(s.state.functions, id) + delete(s.state.quietSuccess, id) + var tokens []*Cancellation + for _, call := range s.state.incoming { + if call.functionID == id { + tokens = append(tokens, call.cancellation) + } + } + s.mu.Unlock() + for _, token := range tokens { + token.Cancel() + } + return nil +} + +// Host is the host services for work outside a function call; usable once +// the session is ready. +func (h *BackendHandle) Host() *Host { return &Host{shared: h.shared} } + +// Credentials is Host().Credentials(). +func (h *BackendHandle) Credentials() *Credentials { return h.Host().Credentials() } diff --git a/internal/lithesdk/lithe/cancellation.go b/internal/lithesdk/lithe/cancellation.go new file mode 100644 index 0000000..3d9b2c1 --- /dev/null +++ b/internal/lithesdk/lithe/cancellation.go @@ -0,0 +1,133 @@ +package lithe + +import ( + "context" + "sync" + "time" +) + +type watcher struct { + id uint64 + callback func() +} + +// Cancellation is a call's cancellation token. Lithe cancels it when the +// host cancels the call, when the call is unregistered, and when the session +// ends. +type Cancellation struct { + mu sync.Mutex + cancelled bool + done chan struct{} + callbacks []watcher + nextWatch uint64 + ctxOnce sync.Once + ctx context.Context +} + +// NewCancellation returns a token that is not cancelled. +func NewCancellation() *Cancellation { + return &Cancellation{done: make(chan struct{})} +} + +// IsCancelled reports whether the token was cancelled. +func (c *Cancellation) IsCancelled() bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.cancelled +} + +// Check returns ErrCancelled once the token was cancelled. +func (c *Cancellation) Check() error { + if c.IsCancelled() { + return ErrCancelled + } + return nil +} + +// Done is closed when the token is cancelled. +func (c *Cancellation) Done() <-chan struct{} { return c.done } + +// Context is a context.Context cancelled with the token, for code that takes +// one, such as exec.CommandContext or http.NewRequestWithContext. Every call +// returns the same context. +func (c *Cancellation) Context() context.Context { + c.ctxOnce.Do(func() { + ctx, cancel := context.WithCancel(context.Background()) + c.ctx = ctx + c.OnCancel(cancel) + }) + return c.ctx +} + +// WaitTimeout waits up to timeout and reports whether the token was +// cancelled. +func (c *Cancellation) WaitTimeout(timeout time.Duration) bool { + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-c.done: + return true + case <-timer.C: + return c.IsCancelled() + } +} + +// OnCancel runs callback once the token is cancelled, at once when it +// already is. +func (c *Cancellation) OnCancel(callback func()) { + c.watch(callback) +} + +// Cancel cancels the token. Only the first call has an effect; callbacks run +// outside the token's lock. +func (c *Cancellation) Cancel() { + c.mu.Lock() + if c.cancelled { + c.mu.Unlock() + return + } + c.cancelled = true + close(c.done) + callbacks := c.callbacks + c.callbacks = nil + c.mu.Unlock() + for _, watch := range callbacks { + watch.callback() + } +} + +// watch registers callback and returns its ID; when the token is already +// cancelled it runs callback and returns false. +func (c *Cancellation) watch(callback func()) (uint64, bool) { + c.mu.Lock() + if c.cancelled { + c.mu.Unlock() + callback() + return 0, false + } + c.nextWatch++ + id := c.nextWatch + c.callbacks = append(c.callbacks, watcher{id, callback}) + c.mu.Unlock() + return id, true +} + +func (c *Cancellation) unwatch(id uint64) { + c.mu.Lock() + for i, watch := range c.callbacks { + if watch.id == id { + c.callbacks = append(c.callbacks[:i:i], c.callbacks[i+1:]...) + break + } + } + c.mu.Unlock() +} + +func anyCancelled(scope []*Cancellation) bool { + for _, token := range scope { + if token.IsCancelled() { + return true + } + } + return false +} diff --git a/internal/lithesdk/lithe/diagnostics.go b/internal/lithesdk/lithe/diagnostics.go new file mode 100644 index 0000000..ae9248c --- /dev/null +++ b/internal/lithesdk/lithe/diagnostics.go @@ -0,0 +1,178 @@ +package lithe + +import ( + "slices" + "strconv" + "time" +) + +// operations are the fixed operations a diagnostic may name besides the +// backend's registered functions. +var operations = []string{ + "initialize", + "shutdown", + "notification", + "function-call", + "result-encoding", + "lithe/build/model", + "lithe/build/dependencies", + "lithe/build/execute", + "lithe/build/test", + "lithe/build/discoverTests", + "lithe/build/prepareRun", + "lithe/build/prepareDebug", + "lithe/build/runEntrypoints", + "lithe/vcs/status", + "lithe/vcs/baseContent", + "lithe/vcs/history", + "lithe/vcs/fileHistory", + "lithe/vcs/annotate", + "lithe/vcs/checkin", + "lithe/vcs/rollback", + "lithe/vcs/update", + "lithe/vcs/fileOperation", + "lithe/vcs/resolve", + "lithe/vcs/cleanup", + methodKeymapImport, +} + +// maxEarlyDiagnostics is how many facts recorded during initialize wait for +// its answer. +const maxEarlyDiagnostics = 8 + +// token reports whether value is 1-maximum ASCII letters, digits, ".", "_", +// ":", "/", "-" or "$". +func token(value string, maximum int) bool { + if value == "" || len(value) > maximum { + return false + } + for i := 0; i < len(value); i++ { + c := value[i] + if !isASCIIAlnum(c) && c != '.' && c != '_' && c != ':' && c != '/' && c != '-' && c != '$' { + return false + } + } + return true +} + +// requestOperationID is the operation ID diagnostics carry: the call's +// operationID when it is a token, otherwise its JSON-RPC ID; "" for none. +func requestOperationID(operationID, requestID any) string { + if id, ok := operationID.(string); ok && token(id, 128) { + return id + } + var fallback string + switch id := requestID.(type) { + case string: + fallback = id + default: + number, ok := integer(id) + if !ok || number > maxSafeInteger || number < -maxSafeInteger { + return "" + } + fallback = strconv.FormatInt(number, 10) + } + if !token(fallback, 128) { + return "" + } + return fallback +} + +// Diagnostics records typed facts in the host's litheLogging catalog over +// the protocol stream, without a queue or file I/O. +type Diagnostics struct { + shared *shared + operationID string +} + +// Degraded records a handled degradation. code is a controlled category, +// never an error message; pass at most one count. +func (d *Diagnostics) Degraded(operation, code string, count ...uint64) error { + return d.record("degraded", operation, &code, first(count), nil) +} + +// Recovered records a real recovery, with the same controlled operation +// and category as Degraded. +func (d *Diagnostics) Recovered(operation, code string, count ...uint64) error { + return d.record("recovered", operation, &code, first(count), nil) +} + +func first(values []uint64) *uint64 { + if len(values) == 0 { + return nil + } + return &values[0] +} + +// terminal records how an operation ended; err is nil for success. +func (d *Diagnostics) terminal(operation string, err error, started time.Time) { + kind := "operationFinished" + var code *string + if err != nil { + kind = "operationFailed" + // A plugin error logs its own code; any other failure only its kind. + category := failureKind(err) + if errorKind, plugin := classify(err); errorKind == kindPlugin { + category = plugin.code + } + code = &category + } + duration := elapsed(started) + _ = d.record(kind, operation, code, nil, &duration) +} + +func elapsed(started time.Time) uint64 { + milliseconds := time.Since(started).Milliseconds() + if milliseconds < 0 { + return 0 + } + return min(uint64(milliseconds), maxSafeInteger) +} + +func (d *Diagnostics) record(kind, operation string, code *string, count, duration *uint64) error { + s := d.shared + s.mu.Lock() + _, registered := s.state.functions[operation] + enabled := s.state.logging + s.mu.Unlock() + if !slices.Contains(operations, operation) && !registered { + return newSdkError("sdk.logging.invalidOperation", "Diagnostics need a registered operation.") + } + if code != nil && !token(*code, 64) { + return newSdkError("sdk.logging.invalidCode", "Diagnostics need a controlled code.") + } + if count != nil && *count > maxSafeInteger { + return newSdkError("sdk.logging.invalidCount", "Diagnostics need a safe count.") + } + if !enabled { + return nil + } + named := operation + if len(named) > 64 { + named = "function-call" + } + params := map[string]any{"kind": kind, "operation": named} + if code != nil { + params["code"] = *code + } + if count != nil { + params["count"] = *count + } + if duration != nil { + params["durationMs"] = *duration + } + if token(d.operationID, 128) { + params["operationId"] = d.operationID + } + s.mu.Lock() + if !s.state.loggingReady { + if len(s.state.earlyDiagnostics) < maxEarlyDiagnostics { + s.state.earlyDiagnostics = append(s.state.earlyDiagnostics, params) + } + s.mu.Unlock() + return nil + } + s.mu.Unlock() + s.write(map[string]any{"jsonrpc": "2.0", "method": methodLog, "params": params}) + return nil +} diff --git a/internal/lithesdk/lithe/errors.go b/internal/lithesdk/lithe/errors.go new file mode 100644 index 0000000..d04c0d5 --- /dev/null +++ b/internal/lithesdk/lithe/errors.go @@ -0,0 +1,236 @@ +package lithe + +import ( + "errors" + "fmt" + "strings" +) + +// SDK error codes a caller may compare against. +const ( + CodeCallCancelled = "sdk.call.cancelled" + CodeSessionClosed = "sdk.session.closed" +) + +// ErrorCode pairs a host or relay error code with its JSON-RPC number. +type ErrorCode struct { + Code string + Number int64 +} + +// HostErrorCodes are the codes Lithe answers host requests with, and the +// number each one travels as. +var HostErrorCodes = []ErrorCode{ + {"plugin.host.unavailable", -32601}, + {"plugin.host.invalidParams", -32602}, + {"plugin.host.failed", -32603}, + {"plugin.host.cancelled", -32800}, + {"plugin.host.permissionDenied", -32010}, + {"plugin.host.contextExpired", -32011}, + {"plugin.host.authorityUnsupported", -32012}, + {"plugin.host.versionConflict", -32013}, + {"plugin.host.limitExceeded", -32014}, + {"plugin.host.timeout", -32015}, + {"plugin.host.notFound", -32016}, + {"plugin.host.readOnly", -32017}, + {"plugin.host.unsupportedOption", -32018}, + {"plugin.host.preconditionFailed", -32019}, + {"plugin.host.busy", -32020}, + {"plugin.host.rateLimited", -32021}, + {"plugin.host.languageServerUnavailable", -32022}, + {"plugin.host.languageServerError", -32023}, + {"plugin.host.methodNotDeclared", -32024}, + {"plugin.host.toolUnresolved", -32025}, + {"plugin.host.foreignContribution", -32026}, + {"plugin.host.remoteDisconnected", -32078}, + {"plugin.host.platformUnavailable", -32079}, + {"plugin.host.alreadyExists", -32080}, + {"plugin.host.diskChanged", -32081}, +} + +// RelayErrorCodes are the codes a cross-plugin call fails with. +var RelayErrorCodes = []ErrorCode{ + {"plugin.function.notDeclared", -32027}, + {"plugin.function.notExported", -32028}, + {"plugin.function.providerDisabled", -32029}, + {"plugin.function.versionMismatch", -32030}, + {"plugin.function.callCycle", -32065}, + {"plugin.function.depthExceeded", -32066}, + {"plugin.function.tooManyCalls", -32067}, + {"plugin.function.payloadTooLarge", -32068}, + {"plugin.function.providerUnavailable", -32069}, + {"plugin.function.failed", -32070}, + {"plugin.function.invalidResult", -32071}, +} + +// PluginError is a failure the plugin reports to the caller with its own +// code; the caller sees the code and the message. +type PluginError struct { + code string + message string +} + +// NewPluginError returns a plugin error. It panics when code is not a +// plugin error code: a code is part of the plugin's API, so a malformed one +// is a programming error. +func NewPluginError(code, message string) *PluginError { + if !IsPluginErrorCode(code) { + panic(fmt.Sprintf("Plugin error code %q must start with a letter, use letters, digits, \".\", \"_\" or \"-\", and be at most 64 bytes.", code)) + } + return &PluginError{code: code, message: message} +} + +// Code is the plugin's error code. +func (e *PluginError) Code() string { return e.code } + +// Message is the text the caller sees. +func (e *PluginError) Message() string { return e.message } + +func (e *PluginError) Error() string { return e.code + ": " + e.message } + +// ErrCancelled ends a call that stopped because it was cancelled. Return it +// (or wrap it) from a handler that saw its cancellation. +var ErrCancelled = errors.New("The call was cancelled.") + +// SdkError is a failure of the SDK or of a host request: a host refusal +// keeps the code, JSON-RPC number and details Lithe sent. +type SdkError struct { + code string + message string + rpcCode *int64 + details map[string]any +} + +func newSdkError(code, message string) *SdkError { + return &SdkError{code: code, message: message} +} + +// Code is the error code, such as "plugin.host.permissionDenied". +func (e *SdkError) Code() string { return e.code } + +// Message is the text of the error. +func (e *SdkError) Message() string { return e.message } + +// RPCCode is the JSON-RPC error number of a host refusal. +func (e *SdkError) RPCCode() (int64, bool) { + if e.rpcCode == nil { + return 0, false + } + return *e.rpcCode, true +} + +// Details are the structured details of a host refusal, or nil. +func (e *SdkError) Details() map[string]any { return e.details } + +func (e *SdkError) Error() string { return e.code + ": " + e.message } + +// Is makes errors.Is(err, ErrCancelled) true for a cancelled host request. +func (e *SdkError) Is(target error) bool { + return target == ErrCancelled && e.code == CodeCallCancelled +} + +func unavailable(message string) *SdkError { + number := int64(rpcMethodNotFound) + return &SdkError{code: "plugin.host.unavailable", message: message, rpcCode: &number} +} + +func cancelledError() *SdkError { + return newSdkError(CodeCallCancelled, "The request was cancelled.") +} + +func closedError() *SdkError { + return newSdkError(CodeSessionClosed, "The session ended.") +} + +// sdkErrorFromResponse maps a JSON-RPC error a host request was answered with. +func sdkErrorFromResponse(method string, value any) *SdkError { + object, _ := value.(map[string]any) + var number *int64 + if raw, ok := object["code"]; ok { + if parsed, ok := integer(raw); ok { + number = &parsed + } + } + data, _ := object["data"].(map[string]any) + code, ok := data["code"].(string) + if !ok { + if strings.HasPrefix(method, hostPrefix) { + code = "plugin.host.failed" + if number != nil { + for _, table := range [][]ErrorCode{HostErrorCodes, RelayErrorCodes} { + for _, known := range table { + if known.Number == *number { + code = known.Code + } + } + } + } + } else { + code = "sdk.host.error" + } + } + message, ok := object["message"].(string) + if !ok { + message = method + " failed." + } + details, _ := data["details"].(map[string]any) + return &SdkError{code: code, message: message, rpcCode: number, details: details} +} + +// errorKind sorts a handler error into the three answers a call can give. +type errorKind int + +const ( + kindPlugin errorKind = iota + kindCancelled + kindInternal +) + +func classify(err error) (errorKind, *PluginError) { + var plugin *PluginError + if errors.As(err, &plugin) { + return kindPlugin, plugin + } + if errors.Is(err, ErrCancelled) { + return kindCancelled, nil + } + return kindInternal, nil +} + +// failureKind is the fixed category a failure is logged with; its text can +// hold user data and is never logged. +func failureKind(err error) string { + switch kind, _ := classify(err); kind { + case kindPlugin: + return "plugin_error" + case kindCancelled: + return "cancelled" + default: + return "internal_error" + } +} + +func cancelledResponse() map[string]any { + return map[string]any{"code": rpcRequestCancelled, "message": "The request was cancelled."} +} + +func internalResponse() map[string]any { + return map[string]any{"code": rpcInternalError, "message": "The plugin backend failed unexpectedly."} +} + +// responseError is the JSON-RPC error a failed call is answered with. An +// internal error's text stays in the backend. +func responseError(err error) map[string]any { + switch kind, plugin := classify(err); kind { + case kindCancelled: + return cancelledResponse() + case kindPlugin: + return map[string]any{ + "code": rpcRequestFailed, + "message": boundedText(plugin.message, maxErrorMessageBytes), + "data": map[string]any{"code": plugin.code}, + } + default: + return internalResponse() + } +} diff --git a/internal/lithesdk/lithe/framing.go b/internal/lithesdk/lithe/framing.go new file mode 100644 index 0000000..bb38eac --- /dev/null +++ b/internal/lithesdk/lithe/framing.go @@ -0,0 +1,111 @@ +package lithe + +import ( + "bufio" + "errors" + "fmt" + "io" + "strconv" + "strings" +) + +const ( + maxHeaderBytes = 8192 + maxMessageBytes = 64 << 20 +) + +// framingError ends the session: the stream can no longer be read in step. +type framingError struct{ message string } + +func (e *framingError) Error() string { return e.message } + +// frame is one message read from the host. A body that is not JSON is +// malformed; the stream stays in step and the session goes on. +type frame struct { + value any + malformed bool +} + +// readFrame reads one Content-Length framed message. It returns nil, nil +// when the input ends between messages. +func readFrame(reader *bufio.Reader) (*frame, error) { + var ( + total int + length string + found bool + started bool + line []byte + finished bool + ) + for !finished { + b, err := reader.ReadByte() + if err != nil { + if errors.Is(err, io.EOF) { + if !started { + return nil, nil + } + return nil, &framingError{"The input ended inside a message header."} + } + return nil, &framingError{"The input failed: " + err.Error()} + } + started = true + total++ + if total > maxHeaderBytes { + return nil, &framingError{"The message header is too long."} + } + if b != '\n' { + line = append(line, b) + continue + } + text := strings.TrimSuffix(string(line), "\r") + line = line[:0] + if text == "" { + finished = true + continue + } + name, value, ok := strings.Cut(text, ":") + if ok && !found && strings.EqualFold(strings.TrimSpace(name), "content-length") { + length, found = strings.TrimSpace(value), true + } + } + size, valid := contentLength(length, found) + if !valid { + return nil, &framingError{"A message has no valid Content-Length header."} + } + if size > maxMessageBytes { + return nil, &framingError{fmt.Sprintf("A message of %d bytes exceeds the %d-byte limit.", size, maxMessageBytes)} + } + body := make([]byte, size) + if _, err := io.ReadFull(reader, body); err != nil { + return nil, &framingError{"The input failed: " + err.Error()} + } + value, err := decodeJSON(body) + if err != nil { + return &frame{malformed: true}, nil + } + return &frame{value: value}, nil +} + +func contentLength(value string, found bool) (uint64, bool) { + if !found || value == "" { + return 0, false + } + for i := 0; i < len(value); i++ { + if value[i] < '0' || value[i] > '9' { + return 0, false + } + } + size, err := strconv.ParseUint(value, 10, 64) + return size, err == nil +} + +// writeFrame writes one framed message and flushes it. +func writeFrame(writer *bufio.Writer, body []byte) error { + if _, err := fmt.Fprintf(writer, "Content-Length: %d\r\n\r\n", len(body)); err != nil { + return err + } + if _, err := writer.Write(body); err != nil { + return err + } + return writer.Flush() +} diff --git a/internal/lithesdk/lithe/host.go b/internal/lithesdk/lithe/host.go new file mode 100644 index 0000000..56cf43b --- /dev/null +++ b/internal/lithesdk/lithe/host.go @@ -0,0 +1,1496 @@ +package lithe + +// Host services of the plugin-function protocol: the lithe/host/* requests a +// backend sends to Lithe, the subscriptions some of them create, and the +// [Host] handlers use. The backend owns the wire; this file owns what Core +// expects of a well-behaved client -- at most 16 unanswered host requests, +// cancellation through $/cancelRequest, and subscription events routed by ID. +// +// Contract: contract/v1/README.md, "Host services" and the host sections +// after it. + +import ( + "encoding/json" + "errors" + "maps" + "math" + "slices" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" +) + +// notNegotiated is the answer Core gives a host request when it did not +// offer litheFunctions. +const notNegotiated = "The host did not negotiate plugin functions (litheFunctions), which offer host services." + +// settled is how a request this backend sent ended: the host's result, or +// an error. +type settled struct { + value any + err error +} + +// outgoing is one request this backend sent to the host, until the host +// answers it. +type outgoing struct { + method string + reply chan settled + // slot is whether it holds one of the 16 host-request slots. A cancelled + // request keeps its slot until the host answers. + slot bool + // route is where the events of the subscription it creates go. + route *route +} + +// channel is the session's host-request state, guarded by shared.mu. +type channel struct { + inFlight int + // waiting are the requests waiting for a free slot, in call order. + waiting []uint64 + nextTicket uint64 + // subscribing counts subscribing requests not yet answered; early events + // wait only while there are some. + subscribing int + routes map[string]*route + early []earlyEvent +} + +type earlyEvent struct { + subscriptionID string + sequence uint64 + event any +} + +type route struct { + live *atomic.Bool + queue *eventQueue + last uint64 +} + +func (r *route) emit(subscriptionID string, sequence uint64, event any) { + gap := r.last == math.MaxUint64 || r.last+1 != sequence + r.last = sequence + r.queue.push(Event{subscriptionID: subscriptionID, sequence: sequence, gap: gap, event: event}) +} + +// refusal is why the state refuses a new request, if it does. The caller +// holds mu. +func refusal(st *state, scope []*Cancellation) error { + switch st.phase { + case phaseReady: + if anyCancelled(scope) { + return cancelledError() + } + return nil + case phaseExited: + return closedError() + default: + return newSdkError("sdk.session.notReady", "The session is not initialized.") + } +} + +// exchange sends a request to the host and waits for its answer, the end of +// the session, or the cancellation of a token in scope. A request with a +// slot first waits its turn among the 16 the host accepts at once. +func (s *shared) exchange(method string, params any, slot bool, scope []*Cancellation, rt *route) (any, error) { + id := "sdk-" + strconv.FormatUint(s.nextRequest.Add(1), 10) + reply := make(chan settled, 1) + abort := make(chan struct{}) + var once sync.Once + wake := func() { once.Do(func() { close(abort) }) } + type watched struct { + token *Cancellation + id uint64 + } + var watches []watched + for _, token := range scope { + if watchID, ok := token.watch(wake); ok { + watches = append(watches, watched{token, watchID}) + } + } + var live *atomic.Bool + if rt != nil { + live = rt.live + } + result, cancelled := s.sendAndWait(id, method, params, slot, scope, rt, reply, abort) + for _, watch := range watches { + watch.token.unwatch(watch.id) + } + if !cancelled { + return result.value, result.err + } + s.mu.Lock() + if live != nil { + // Answered just before the cancellation won. + for subscriptionID, existing := range s.state.channel.routes { + if existing.live == live { + delete(s.state.channel.routes, subscriptionID) + existing.queue.close() + } + } + } + entry, pending := s.state.outgoing[id] + if pending { + entry.route = nil + } + negotiated := s.state.functionsNegotiated + s.mu.Unlock() + if pending && negotiated { + s.write(map[string]any{"jsonrpc": "2.0", "method": methodCancelRequest, "params": map[string]any{"id": id}}) + } + // A cancelled mutation may already have taken effect; it is never sent + // again. + return nil, cancelledError() +} + +// sendAndWait reports true when a token in scope was cancelled while the +// request was on the wire. +func (s *shared) sendAndWait(id, method string, params any, slot bool, scope []*Cancellation, rt *route, reply chan settled, abort chan struct{}) (settled, bool) { + s.mu.Lock() + if slot { + ticket := s.state.channel.nextTicket + s.state.channel.nextTicket++ + s.state.channel.waiting = append(s.state.channel.waiting, ticket) + for { + if err := refusal(&s.state, scope); err != nil { + s.state.channel.waiting = slices.DeleteFunc(s.state.channel.waiting, func(waiting uint64) bool { return waiting == ticket }) + s.notifySlots() + s.mu.Unlock() + return settled{err: err}, false + } + if s.state.channel.inFlight < maxPendingHostCalls && s.state.channel.waiting[0] == ticket { + break + } + signal := s.state.slotSignal + s.mu.Unlock() + select { + case <-signal: + case <-abort: + } + s.mu.Lock() + } + s.state.channel.waiting = s.state.channel.waiting[1:] + s.state.channel.inFlight++ + s.notifySlots() + } else if err := refusal(&s.state, scope); err != nil { + s.mu.Unlock() + return settled{err: err}, false + } + s.state.outgoing[id] = &outgoing{method: method, reply: reply, slot: slot, route: rt} + s.mu.Unlock() + message := map[string]any{"jsonrpc": "2.0", "id": id, "method": method} + if params != nil { + message["params"] = params + } + s.write(message) + select { + case result := <-reply: + return result, false + case <-abort: + select { + case result := <-reply: + return result, false + default: + return settled{}, true + } + } +} + +// settleOutgoing settles the request a host response answers. +func (s *shared) settleOutgoing(id any, message map[string]any) { + key, ok := id.(string) + if !ok { + return + } + s.mu.Lock() + entry, ok := s.state.outgoing[key] + if !ok { + s.mu.Unlock() + return + } + delete(s.state.outgoing, key) + if entry.slot { + s.state.channel.inFlight-- + s.notifySlots() + } + var result settled + if failure := message["error"]; failure != nil { + result.err = sdkErrorFromResponse(entry.method, failure) + } else { + result.value = message["result"] + } + if result.err == nil && entry.route != nil { + subscriptionID, ok := field(result.value, "subscriptionID").(string) + if ok && IsCredentialKey(subscriptionID) { + ch := &s.state.channel + var rest []earlyEvent + // Events the host sent before this answer. + for _, early := range ch.early { + if early.subscriptionID == subscriptionID { + entry.route.emit(subscriptionID, early.sequence, early.event) + } else { + rest = append(rest, early) + } + } + ch.early = rest + if old := ch.routes[subscriptionID]; old != nil { + old.queue.close() + } + ch.routes[subscriptionID] = entry.route + } else { + result = settled{err: newSdkError("sdk.host.invalidResult", entry.method+" answered without a subscriptionID.")} + } + } + s.mu.Unlock() + entry.reply <- result +} + +// deliver routes one lithe/host/subscriptions/notify. +func (s *shared) deliver(params map[string]any) { + subscriptionID, ok := params["subscriptionID"].(string) + if !ok { + return + } + sequence, _ := unsignedInteger(params["sequence"]) + event := params["event"] + s.mu.Lock() + ch := &s.state.channel + if rt := ch.routes[subscriptionID]; rt != nil { + rt.emit(subscriptionID, sequence, event) + } else if ch.subscribing > 0 { + if len(ch.early) >= maxEarlyEvents { + s.mu.Unlock() + s.failed("notification", "subscription_queue_full") + return + } + ch.early = append(ch.early, earlyEvent{subscriptionID, sequence, event}) + } + // Otherwise the subscription was disposed; nothing follows a disposal. + s.mu.Unlock() +} + +// closeChannel ends every host request and subscription with the session. +// The caller holds mu. +func (s *shared) closeChannel() { + for id, entry := range s.state.outgoing { + delete(s.state.outgoing, id) + entry.reply <- settled{err: closedError()} + } + for id, rt := range s.state.channel.routes { + delete(s.state.channel.routes, id) + rt.live.Store(false) + rt.queue.close() + } + s.state.channel.early = nil + s.notifySlots() +} + +// dispose stops routing a subscription's events at once and asks the host +// to dispose it. live limits the first step to one subscription object. +func (s *shared) dispose(subscriptionID string, live *atomic.Bool) error { + s.mu.Lock() + routes := s.state.channel.routes + if rt := routes[subscriptionID]; rt != nil && (live == nil || rt.live == live) { + delete(routes, subscriptionID) + rt.live.Store(false) + rt.queue.close() + } + ready := s.state.phase == phaseReady + s.mu.Unlock() + if !ready { + return nil + } + _, err := (&Host{shared: s}).request(methodDispose, map[string]any{"subscriptionID": subscriptionID}) + return err +} + +// Host is the host services (lithe/host/*): credentials; workspace contexts, +// files, documents, the editor, previews, the browser, messages, terminals +// and capability discovery; calls to other plugins' functions. They are +// available when the host offered litheFunctions. Every method blocks until +// the host answers; failures the host reports carry its error.data.code, +// such as plugin.host.contextExpired. +// +// [BackendHandle.Host] is usable once the session is ready. A handler's +// [Context.Host] belongs to its call: requests still unanswered when the +// call is cancelled or ends fail with sdk.call.cancelled and are cancelled +// on the wire. At most 16 requests are on the wire at once; the rest wait +// their turn. +// +// Results are JSON as the host sent it; unmarshal them into the types you +// need. +type Host struct { + shared *shared + scope []*Cancellation + // parentOperation is the operationID of the relayed call this host + // serves, if any; the default parentOperationID of its cross-plugin + // calls. + parentOperation string +} + +// Negotiated reports whether the host offered litheFunctions, and with it +// host services, in this session; false before initialize. +func (h *Host) Negotiated() bool { return h.shared.functionsNegotiated() } + +// WithCancellation returns the same services, with requests also cancelled +// by cancellation, for work a plugin may stop for its own reasons. +func (h *Host) WithCancellation(cancellation *Cancellation) *Host { + scope := append(slices.Clone(h.scope), cancellation) + return &Host{shared: h.shared, scope: scope, parentOperation: h.parentOperation} +} + +// Request sends any lithe/host/* request, including methods a later host +// adds; [Host.Supports] says whether the session may call it. params is +// any JSON-serializable value; nil sends no params. +func (h *Host) Request(method string, params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + result, err := h.request(method, value) + if err != nil { + return nil, err + } + return raw(result), nil +} + +// Subscribe sends a request that answers { subscriptionID } and routes the +// subscription's events to the returned [Subscription]. +func (h *Host) Subscribe(method string, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + return h.subscribe(method, value) +} + +// Capabilities is { protocolVersion, backendAuthority, services, limits }, +// asked once per session. +func (h *Host) Capabilities() (json.RawMessage, error) { + capabilities, err := h.capabilitiesValue() + if err != nil { + return nil, err + } + return raw(capabilities), nil +} + +// Supports reports whether this session may call method, from +// [Host.Capabilities]. A missing grant still fails the request. Without +// litheFunctions nothing is supported. +func (h *Host) Supports(method string) (bool, error) { + if !h.Negotiated() { + return false, nil + } + capabilities, err := h.capabilitiesValue() + if err != nil { + return false, err + } + services, _ := field(capabilities, "services").(map[string]any) + for _, service := range services { + methods, _ := field(service, "methods").([]any) + for _, entry := range methods { + if name, ok := entry.(string); ok && name == method { + return true, nil + } + } + } + return false, nil +} + +func (h *Host) capabilitiesValue() (any, error) { + if !h.Negotiated() { + return nil, unavailable(notNegotiated) + } + s := h.shared + // Held during the request, so concurrent callers share one answer. + s.capabilitiesMu.Lock() + defer s.capabilitiesMu.Unlock() + if s.capabilities != nil { + return s.capabilities, nil + } + capabilities, err := h.request(methodCapabilities, nil) + if err != nil { + return nil, err + } + if _, ok := capabilities.(map[string]any); !ok { + return nil, newSdkError("sdk.host.invalidResult", "lithe/host/getCapabilities answered with something other than an object.") + } + s.capabilities = capabilities + return capabilities, nil +} + +// Credentials is the host's credentials service. +func (h *Host) Credentials() *Credentials { return &Credentials{host: h} } + +// Subscriptions disposes subscriptions by ID. +func (h *Host) Subscriptions() *Subscriptions { return &Subscriptions{host: h} } + +// Workspace is workspace contexts and files. +func (h *Host) Workspace() *Workspace { return &Workspace{host: h} } + +// Documents is open documents, read from their live buffers. +func (h *Host) Documents() *Documents { return &Documents{host: h} } + +// Editor is the text editor. +func (h *Host) Editor() *Editor { return &Editor{host: h} } + +// Preview is Markdown and HTML previews. +func (h *Host) Preview() *Preview { return &Preview{host: h} } + +// Browser is the system browser. +func (h *Host) Browser() *Browser { return &Browser{host: h} } + +// Terminal is integrated native terminals. +func (h *Host) Terminal() *Terminal { return &Terminal{host: h} } + +// Window is messages in the window. +func (h *Host) Window() *Window { return &Window{host: h} } + +// Functions is calls to other plugins' functions through Core. +func (h *Host) Functions() *Functions { return &Functions{host: h} } + +// request sends a host request whose params are already in the SDK's +// dynamic form. +func (h *Host) request(method string, params any) (any, error) { + return h.send(method, params, nil) +} + +func (h *Host) subscribe(method string, params any) (*Subscription, error) { + live := &atomic.Bool{} + live.Store(true) + rt := &route{live: live, queue: newEventQueue()} + s := h.shared + s.mu.Lock() + s.state.channel.subscribing++ + s.mu.Unlock() + result, err := h.send(method, params, rt) + s.mu.Lock() + s.state.channel.subscribing-- + if s.state.channel.subscribing == 0 { + s.state.channel.early = nil + } + s.mu.Unlock() + if err != nil { + return nil, err + } + id, _ := field(result, "subscriptionID").(string) + return &Subscription{id: id, shared: s, live: live, queue: rt.queue}, nil +} + +func (h *Host) send(method string, params any, rt *route) (any, error) { + if !strings.HasPrefix(method, hostPrefix) { + return nil, newSdkError("sdk.host.method", method+" is not a host method; host requests are lithe/host/*.") + } + s := h.shared + s.mu.Lock() + err := refusal(&s.state, nil) + s.mu.Unlock() + if err != nil { + return nil, err + } + if !h.Negotiated() { + // The answer Core would give, without the round trip. + return nil, unavailable(notNegotiated) + } + if anyCancelled(h.scope) { + return nil, cancelledError() + } + return s.exchange(method, params, true, h.scope, rt) +} + +// scoped sends a method whose params name a workspace context; it answers +// an object or null. +func (h *Host) scoped(method string, context WorkspaceContext, params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return h.objectOrNull(method, value) +} + +func (h *Host) objectOrNull(method string, params any) (json.RawMessage, error) { + result, err := h.request(method, params) + if err != nil { + return nil, err + } + switch result.(type) { + case nil, map[string]any: + return raw(result), nil + } + return nil, invalidResult(method) +} + +// requestObject sends a method that always answers an object. +func (h *Host) requestObject(method string, params any) (json.RawMessage, error) { + result, err := h.request(method, params) + if err != nil { + return nil, err + } + if _, ok := result.(map[string]any); !ok { + return nil, invalidResult(method) + } + return raw(result), nil +} + +func invalidResult(method string) *SdkError { + return newSdkError("sdk.host.invalidResult", method+" answered with something other than an object.") +} + +func invalidHostParams() *SdkError { + return newSdkError("sdk.host.invalidParams", "Host request params are an object.") +} + +// withContext is params with context added; params are an object or nil. +func withContext(context WorkspaceContext, params any) (any, error) { + var object map[string]any + switch value := params.(type) { + case nil: + object = map[string]any{} + case map[string]any: + object = maps.Clone(value) + default: + return nil, invalidHostParams() + } + object["context"] = context.toValue() + return object, nil +} + +// WorkspaceContext is a workspace context reference, { contextID, +// generation }: the window a call or command ran in, or one from +// ListContexts. A context is replaced when its window's folders change; +// requests with an old generation fail with plugin.host.contextExpired. +type WorkspaceContext struct { + contextID string + generation uint64 +} + +func invalidContext() *SdkError { + return newSdkError("sdk.host.invalidContext", "A context is { contextID, generation }: an ID of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\", and a positive generation.") +} + +// NewWorkspaceContext returns a context reference. contextID is 1-128 ASCII +// letters, digits, ".", "_", ":" or "-"; generation is positive. +func NewWorkspaceContext(contextID string, generation uint64) (WorkspaceContext, error) { + return ParseWorkspaceContext(map[string]any{"contextID": contextID, "generation": generation}) +} + +// ParseWorkspaceContext reads the reference of a context reference or of a +// full context from ListContexts or GetContext -- a json.RawMessage, a map, +// or any value that serializes to one -- so either can be passed on. +func ParseWorkspaceContext(value any) (WorkspaceContext, error) { + decoded, err := toValue(value) + if err != nil { + return WorkspaceContext{}, invalidContext() + } + return workspaceContextFromValue(decoded) +} + +func workspaceContextFromValue(value any) (WorkspaceContext, error) { + contextID, ok := field(value, "contextID").(string) + if !ok || !IsCredentialKey(contextID) { + return WorkspaceContext{}, invalidContext() + } + number, ok := generation(field(value, "generation")) + if !ok { + return WorkspaceContext{}, invalidContext() + } + return WorkspaceContext{contextID: contextID, generation: number}, nil +} + +// workspaceContextFromReference reads the context of an invocation or +// command: exactly a reference. +func workspaceContextFromReference(value any) *WorkspaceContext { + object, ok := value.(map[string]any) + if !ok || len(object) != 2 { + return nil + } + context, err := workspaceContextFromValue(object) + if err != nil { + return nil + } + return &context +} + +// ID is the context's ID. +func (c WorkspaceContext) ID() string { return c.contextID } + +// Generation is the context's generation. +func (c WorkspaceContext) Generation() uint64 { return c.generation } + +func (c WorkspaceContext) toValue() map[string]any { + return map[string]any{"contextID": c.contextID, "generation": c.generation} +} + +// MarshalJSON writes { "contextID": ..., "generation": ... }. +func (c WorkspaceContext) MarshalJSON() ([]byte, error) { return encodeJSON(c.toValue()) } + +// UnmarshalJSON reads a context reference or a full context. +func (c *WorkspaceContext) UnmarshalJSON(data []byte) error { + value, err := decodeJSON(data) + if err != nil { + return invalidContext() + } + context, err := workspaceContextFromValue(value) + if err != nil { + return err + } + *c = context + return nil +} + +// Event is one lithe/host/subscriptions/notify. +type Event struct { + subscriptionID string + sequence uint64 + gap bool + event any +} + +// SubscriptionID is the subscription the event belongs to. +func (e Event) SubscriptionID() string { return e.subscriptionID } + +// Sequence starts at 1 and grows by one per event of the subscription. +func (e Event) Sequence() uint64 { return e.sequence } + +// Gap is true when events before this one were lost, so state built from +// earlier events should be refreshed, for example by rescanning. +func (e Event) Gap() bool { return e.gap } + +// Event is the event, usually an object. +func (e Event) Event() json.RawMessage { return raw(e.event) } + +// Errors of [Subscription.RecvTimeout]. +var ( + // ErrSubscriptionDisposed: the subscription was disposed or the session + // ended. + ErrSubscriptionDisposed = errors.New("The subscription was disposed.") + // ErrRecvTimeout: no event arrived in time. + ErrRecvTimeout = errors.New("No subscription event arrived in time.") +) + +// eventQueue is an unbounded queue of one subscription's events, in order. +type eventQueue struct { + mu sync.Mutex + items []Event + closed bool + // signal is closed, and replaced, when the queue changes. + signal chan struct{} +} + +func newEventQueue() *eventQueue { + return &eventQueue{signal: make(chan struct{})} +} + +func (q *eventQueue) changed() { + close(q.signal) + q.signal = make(chan struct{}) +} + +func (q *eventQueue) push(event Event) { + q.mu.Lock() + defer q.mu.Unlock() + if q.closed { + return + } + q.items = append(q.items, event) + q.changed() +} + +func (q *eventQueue) close() { + q.mu.Lock() + defer q.mu.Unlock() + if q.closed { + return + } + q.closed = true + q.changed() +} + +// pop waits for the next event: at most timeout when it is positive, else +// without a limit. It fails with ErrSubscriptionDisposed once the queue is +// closed and empty, and ErrRecvTimeout when the time ran out. +func (q *eventQueue) pop(timeout time.Duration) (Event, error) { + var expired <-chan time.Time + if timeout > 0 { + timer := time.NewTimer(timeout) + defer timer.Stop() + expired = timer.C + } + for { + q.mu.Lock() + if len(q.items) > 0 { + event := q.items[0] + q.items[0] = Event{} + q.items = q.items[1:] + q.mu.Unlock() + return event, nil + } + if q.closed { + q.mu.Unlock() + return Event{}, ErrSubscriptionDisposed + } + signal := q.signal + q.mu.Unlock() + select { + case <-signal: + case <-expired: + return Event{}, ErrRecvTimeout + } + } +} + +// Subscription is a host subscription, such as a file watch or registered +// editor actions. Events queue in order until read; dropping the +// subscription does not dispose it on the host, [Subscription.Dispose] does. +type Subscription struct { + id string + shared *shared + live *atomic.Bool + queue *eventQueue +} + +// ID is the subscription's ID. +func (s *Subscription) ID() string { return s.id } + +// IsDisposed is true once disposed here or the session ended. +func (s *Subscription) IsDisposed() bool { return !s.live.Load() } + +// Recv waits for the next event; false once disposed or the session ended. +func (s *Subscription) Recv() (Event, bool) { + event, err := s.queue.pop(0) + if err != nil || s.IsDisposed() { + return Event{}, false + } + return event, true +} + +// RecvTimeout waits at most timeout for the next event. It fails with +// ErrSubscriptionDisposed once disposed or the session ended, and with +// ErrRecvTimeout when no event arrived in time. +func (s *Subscription) RecvTimeout(timeout time.Duration) (Event, error) { + if s.IsDisposed() { + return Event{}, ErrSubscriptionDisposed + } + if timeout <= 0 { + timeout = time.Nanosecond + } + event, err := s.queue.pop(timeout) + if err != nil { + return Event{}, err + } + if s.IsDisposed() { + return Event{}, ErrSubscriptionDisposed + } + return event, nil +} + +// Dispose stops routing events at once and asks the host to dispose the +// subscription. After the session ended there is nothing to ask. +func (s *Subscription) Dispose() error { return s.shared.dispose(s.id, s.live) } + +// Credentials is the host's credentials service: secrets private to this +// plugin, kept in the platform's secret store, never in ${stateDir}. It +// needs the credentials.store permission; without it every request fails +// with plugin.host.permissionDenied. +type Credentials struct{ host *Host } + +// Get returns the secret stored under key, with false when there is none. +func (c *Credentials) Get(key string) (string, bool, error) { + if err := checkCredentialKey(key); err != nil { + return "", false, err + } + result, err := c.host.request(methodCredentialsGet, map[string]any{"key": key}) + if err != nil { + return "", false, err + } + switch value := result.(type) { + case nil: + return "", false, nil + case map[string]any: + if secret, ok := value["secret"].(string); ok { + return secret, true, nil + } + } + return "", false, newSdkError("sdk.host.invalidResult", "The host answered credentials/get without a secret.") +} + +// Set stores secret (at most 16 KiB) under key, replacing any value. +func (c *Credentials) Set(key, secret string) error { + if err := checkCredentialKey(key); err != nil { + return err + } + if len(secret) > maxSecretBytes { + return newSdkError("sdk.credentials.invalidSecret", "A secret is a string of at most 16 KiB.") + } + _, err := c.host.request(methodCredentialsSet, map[string]any{"key": key, "secret": secret}) + return err +} + +// Delete removes the secret under key; it succeeds when nothing was stored. +func (c *Credentials) Delete(key string) error { + if err := checkCredentialKey(key); err != nil { + return err + } + _, err := c.host.request(methodCredentialsDel, map[string]any{"key": key}) + return err +} + +func checkCredentialKey(key string) error { + if IsCredentialKey(key) { + return nil + } + return newSdkError("sdk.credentials.invalidKey", "A credential key is 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".") +} + +// Subscriptions disposes subscriptions by ID. +type Subscriptions struct{ host *Host } + +// Dispose disposes a subscription by ID; it also succeeds for an unknown or +// disposed one. +func (s *Subscriptions) Dispose(subscriptionID string) error { + return s.host.shared.dispose(subscriptionID, nil) +} + +// Workspace is workspace contexts and files. Every method but ListContexts +// names a context: the call's [Context.WorkspaceContext], or one from +// ListContexts read with [ParseWorkspaceContext]. params is any +// JSON-serializable object, nil for none. +type Workspace struct{ host *Host } + +// ListContexts answers { revision, contexts }. +func (w *Workspace) ListContexts() (json.RawMessage, error) { + return w.host.objectOrNull(methodListContexts, map[string]any{}) +} + +// GetContext answers the context. +func (w *Workspace) GetContext(context WorkspaceContext) (json.RawMessage, error) { + return w.host.scoped(methodGetContext, context, nil) +} + +// GetFolders answers { folders }. +func (w *Workspace) GetFolders(context WorkspaceContext) (json.RawMessage, error) { + return w.host.scoped(methodGetFolders, context, nil) +} + +// HostPath is an absolute path on the remote host of a remote context, read +// with [Workspace.GetHostPaths]. It is not a path on this machine: give it +// only to a process that runs on that host, never to os, filepath or exec +// here. It is its own type so it is not passed as a local path by mistake. +type HostPath string + +// String is the path as text. +func (p HostPath) String() string { return string(p) } + +// HostFolder is a root of a remote context and its path on the remote host. +type HostFolder struct { + RootID string `json:"rootID"` + HostPath HostPath `json:"hostPath"` +} + +// GetHostPaths answers the path on the remote host of each root of a remote +// context, or of rootIDs only: 1-256 distinct root IDs from GetFolders. It +// needs the workspace.metadata permission, and only a host that serves it +// lists it, so check Supports("lithe/host/workspace/getHostPaths") first. A +// local context, or a host that cannot answer, fails with +// plugin.host.authorityUnsupported. +func (w *Workspace) GetHostPaths(context WorkspaceContext, rootIDs ...string) ([]HostFolder, error) { + params := map[string]any{"context": context.toValue()} + if len(rootIDs) > 0 { + if !distinctRootIDs(rootIDs) { + return nil, newSdkError("sdk.host.invalidParams", "rootIDs is 1-256 distinct root IDs of 1-128 ASCII letters, digits, \".\", \"_\", \":\" or \"-\".") + } + ids := make([]any, len(rootIDs)) + for i, id := range rootIDs { + ids[i] = id + } + params["rootIDs"] = ids + } + result, err := w.host.request(methodGetHostPaths, params) + if err != nil { + return nil, err + } + return hostFolders(result) +} + +// ProcessRoot is a root of a context as a process started for it names its +// working directory: Path for a local context, HostPath for a remote one. +// The other one is empty. +type ProcessRoot struct { + RootID string `json:"rootID"` + Path string `json:"path,omitempty"` + HostPath HostPath `json:"hostPath,omitempty"` +} + +// ProcessRoots answers the roots of a full context from ListContexts or +// GetContext -- a json.RawMessage, a map, or any value that serializes to +// one. A local context's folders are read without asking the host; for any +// other authority it calls GetHostPaths. +func (w *Workspace) ProcessRoots(context any) ([]ProcessRoot, error) { + value, err := toValue(context) + kind, ok := pointer(value, "authority", "kind").(string) + if err != nil || !ok { + return nil, newSdkError("sdk.host.invalidContext", "ProcessRoots takes a full context, with its authority and folders, from ListContexts or GetContext.") + } + if kind == "local" { + return localFolders(field(value, "folders")) + } + reference, err := workspaceContextFromValue(value) + if err != nil { + return nil, err + } + folders, err := w.GetHostPaths(reference) + if err != nil { + return nil, err + } + roots := make([]ProcessRoot, len(folders)) + for i, folder := range folders { + roots[i] = ProcessRoot{RootID: folder.RootID, HostPath: folder.HostPath} + } + return roots, nil +} + +func distinctRootIDs(rootIDs []string) bool { + if len(rootIDs) > maxHostPathRoots { + return false + } + seen := make(map[string]bool, len(rootIDs)) + for _, id := range rootIDs { + if !IsCredentialKey(id) || seen[id] { + return false + } + seen[id] = true + } + return true +} + +// hostFolders reads { folders: [{ rootID, hostPath }] } of a GetHostPaths +// answer. +func hostFolders(result any) ([]HostFolder, error) { + items, ok := field(result, "folders").([]any) + if !ok { + return nil, invalidHostPaths() + } + folders := make([]HostFolder, len(items)) + for i, item := range items { + rootID, _ := field(item, "rootID").(string) + path, _ := field(item, "hostPath").(string) + if !IsCredentialKey(rootID) || !strings.HasPrefix(path, "/") { + return nil, invalidHostPaths() + } + folders[i] = HostFolder{RootID: rootID, HostPath: HostPath(path)} + } + return folders, nil +} + +func invalidHostPaths() *SdkError { + return newSdkError("sdk.host.invalidResult", "The host answered getHostPaths without folders of a root ID and an absolute host path.") +} + +// localFolders reads [{ rootID, path }] of a local context's folders. +func localFolders(value any) ([]ProcessRoot, error) { + items, ok := value.([]any) + if !ok { + return nil, invalidLocalFolders() + } + roots := make([]ProcessRoot, len(items)) + for i, item := range items { + rootID, _ := field(item, "rootID").(string) + path, ok := field(item, "path").(string) + if !IsCredentialKey(rootID) || !ok { + return nil, invalidLocalFolders() + } + roots[i] = ProcessRoot{RootID: rootID, Path: path} + } + return roots, nil +} + +func invalidLocalFolders() *SdkError { + return newSdkError("sdk.host.invalidContext", "A local context's folders each carry a rootID and a path.") +} + +// ReadDirectory takes resource, cursor?, limit?. +func (w *Workspace) ReadDirectory(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodReadDirectory, context, params) +} + +// Stat takes resource. +func (w *Workspace) Stat(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodStat, context, params) +} + +// ReadFile takes resource, maximumBytes?. +func (w *Workspace) ReadFile(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodReadFile, context, params) +} + +// Watch watches resource, recursive?; events are { rootID, changedPaths, +// requiresRescan }. +func (w *Workspace) Watch(context WorkspaceContext, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return w.host.subscribe(methodWatch, value) +} + +// FindFiles takes a root resource, query, fileMask?, cursor?, limit?. +func (w *Workspace) FindFiles(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodFindFiles, context, params) +} + +// FindText takes a root resource, pattern, and optional search options. +func (w *Workspace) FindText(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodFindText, context, params) +} + +// Create takes resource, kind ("file", "directory" or "symlink"), text? for a +// file and linkTarget for a symlink, and answers { resource, kind }. A link +// stores linkTarget verbatim, absolute or relative to the link's directory, +// and makes nothing outside the root readable. It never overwrites: an +// existing resource is plugin.host.alreadyExists. +func (w *Workspace) Create(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodCreate, context, params) +} + +// Rename takes resource and target, the full new path, and answers +// { resource }. The host saves the open documents under resource first, and +// they follow the file. +func (w *Workspace) Rename(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodRename, context, params) +} + +// Copy takes resource and target, a path that does not exist, and answers +// { resource } of the copy. +func (w *Workspace) Copy(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodCopy, context, params) +} + +// Trash takes resource and moves it to the system trash after saving and +// closing its open documents; nothing is deleted permanently. +func (w *Workspace) Trash(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodTrash, context, params) +} + +// Documents is open documents, read from their live buffers. +type Documents struct{ host *Host } + +// List answers { documents }. +func (d *Documents) List(context WorkspaceContext) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsList, context, nil) +} + +// GetSnapshot takes documentID and answers { document, text }. +func (d *Documents) GetSnapshot(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsSnap, context, params) +} + +// Save takes documentID, expectedVersion? and answers { document } after the +// write. A file changed on disk is plugin.host.diskChanged, and nothing is +// written. +func (d *Documents) Save(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsSave, context, params) +} + +// SaveAs takes documentID and target, a path that does not exist, and answers +// { document } of the new file, which the host opens. +func (d *Documents) SaveAs(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsAs, context, params) +} + +// Close takes documentID, saves the document and then closes its tab; it +// never discards the user's edits. +func (d *Documents) Close(context WorkspaceContext, params any) (json.RawMessage, error) { + return d.host.scoped(methodDocumentsClose, context, params) +} + +// Editor is the text editor. +type Editor struct{ host *Host } + +// GetActive answers the foreground text tab's document summary, or null. +func (e *Editor) GetActive(context WorkspaceContext) (json.RawMessage, error) { + return e.host.scoped(methodEditorActive, context, nil) +} + +// GetSelections takes documentID. +func (e *Editor) GetSelections(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorSelect, context, params) +} + +// ApplyEdits takes documentID, expectedVersion, edits. +func (e *Editor) ApplyEdits(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorApply, context, params) +} + +// ReplaceSelections takes documentID, expectedVersion, selections, +// replacements. +func (e *Editor) ReplaceSelections(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorReplace, context, params) +} + +// InsertText takes documentID, expectedVersion, at, text. +func (e *Editor) InsertText(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorInsert, context, params) +} + +// Open takes resource, activation?, range?, tab?. +func (e *Editor) Open(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorOpen, context, params) +} + +// Reveal takes resource, activation?, range?, tab?. +func (e *Editor) Reveal(context WorkspaceContext, params any) (json.RawMessage, error) { + return e.host.scoped(methodEditorReveal, context, params) +} + +// RegisterActions registers editor actions (id, function, selector) that +// invoke one of the backend's functions; disposing the subscription removes +// them. +func (e *Editor) RegisterActions(context WorkspaceContext, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + if value, err = withContext(context, value); err != nil { + return nil, err + } + return e.host.subscribe(methodEditorActions, value) +} + +// Preview is Markdown and HTML previews. +type Preview struct{ host *Host } + +// OpenHTML takes an HTML resource or inline id/title/text, plus presentation?, range?. +func (p *Preview) OpenHTML(context WorkspaceContext, params any) (json.RawMessage, error) { + return p.host.scoped(methodPreviewHTML, context, params) +} + +// Browser is the system browser. +type Browser struct{ host *Host } + +// OpenExternal takes exactly one of an HTTP(S) url or an HTML resource. +func (b *Browser) OpenExternal(context WorkspaceContext, params any) (json.RawMessage, error) { + return b.host.scoped(methodBrowserOpen, context, params) +} + +// Window is messages in the window. params: text, actions?; each method +// answers { selectedIndex }, null on dismissal. +type Window struct{ host *Host } + +// ShowInformation shows an information message. +func (w *Window) ShowInformation(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowInfo, context, params) +} + +// ShowWarning shows a warning message. +func (w *Window) ShowWarning(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowWarning, context, params) +} + +// ShowError shows an error message. +func (w *Window) ShowError(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodShowError, context, params) +} + +// Terminal is integrated native terminals owned by this backend session and +// workspace. Permission terminal.create; discover each method with +// [Host.Supports]. Input and output stay in the host terminal, not in the +// plugin's web page. +type Terminal struct{ host *Host } + +// Create launches executable and arguments directly. params: executable, +// optional arguments, title, cwd resource, environment, and show (true). +func (t *Terminal) Create(context WorkspaceContext, params any) (json.RawMessage, error) { + return t.host.scoped(methodTerminalCreate, context, params) +} + +// Show shows an owned terminal in its original window without raising the +// window. +func (t *Terminal) Show(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalShow, context, map[string]any{"terminalID": terminalID}) +} + +// Close stops the native process, keeping a bounded display suffix for +// reopen. One retainedContextBytes (0-262144) overrides the create-time +// choice. +func (t *Terminal) Close(context WorkspaceContext, terminalID string, retainedContextBytes ...uint64) (json.RawMessage, error) { + params := map[string]any{"terminalID": terminalID} + if len(retainedContextBytes) > 0 { + params["retainedContextBytes"] = retainedContextBytes[0] + } + return t.host.scoped(methodTerminalClose, context, params) +} + +// Reopen starts the saved argv again and restores plain display history, +// never input. +func (t *Terminal) Reopen(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalReopen, context, map[string]any{"terminalID": terminalID}) +} + +// Dispose permanently forgets an owned handle and its history, also closing +// it if live. +func (t *Terminal) Dispose(context WorkspaceContext, terminalID string) (json.RawMessage, error) { + return t.host.scoped(methodTerminalDrop, context, map[string]any{"terminalID": terminalID}) +} + +// OnExit subscribes to one exit event per process generation, including the +// latest recorded outcome when subscribing after exit. Disposing the +// subscription stops notifications, not the terminal itself. +func (t *Terminal) OnExit(context WorkspaceContext, terminalID string) (*Subscription, error) { + params, err := withContext(context, map[string]any{"terminalID": terminalID}) + if err != nil { + return nil, err + } + return t.host.subscribe(methodTerminalExit, params) +} + +// Functions is calls to the functions other plugins export, relayed by +// Core. It needs a call the plugin declares as pluginFunctions.calls in its +// manifest; discover the methods with [Host.Supports]. The relay accepts +// local workspaces only. +type Functions struct{ host *Host } + +// Providers answers { providers }: the enabled plugins other than this one +// that export functionID, sorted by plugin ID, each { pluginID, version }. +// This plugin must have declared the function. +func (f *Functions) Providers(functionID string) (json.RawMessage, error) { + if !IsFunctionID(functionID) { + return nil, invalidCall("functionID is a plugin function ID.") + } + return f.host.requestObject(methodProviders, map[string]any{"functionID": functionID}) +} + +// Invoke calls one provider and answers { value }, the provider's result. +// call is an object with pluginID and functionID, and optionally params (an +// object), timeoutMilliseconds (a positive integer; the host defaults it +// and caps it at 600000), and parentOperationID; any other key is not sent. +// context is a workspace context this backend learned from the workspace +// service. +// +// Inside a handler, parentOperationID defaults to the operationID of the +// call the handler serves, which tells Core the new call belongs to it. A +// [BackendHandle.Host] serves no call, so it sends the field only when call +// sets it. Cancelling the handler's call cancels the relayed call. +func (f *Functions) Invoke(context WorkspaceContext, call any) (json.RawMessage, error) { + value, err := toValue(call) + if err != nil { + return nil, invalidCall("A cross-plugin call is an object.") + } + relayed, err := relayParams(value, f.host.parentOperation) + if err != nil { + return nil, err + } + params, err := withContext(context, relayed) + if err != nil { + return nil, err + } + return f.host.requestObject(methodRelayInvoke, params) +} + +func invalidCall(message string) *SdkError { + return newSdkError("sdk.functions.invalidCall", message) +} + +// relayParams is the params of lithe/host/functions/invoke for call, +// without its context: the fields the method defines and no other, so the +// host never answers -32018. serving is the operationID parentOperationID +// defaults to, "" for none. +func relayParams(call any, serving string) (map[string]any, error) { + object, ok := call.(map[string]any) + if !ok { + return nil, invalidCall("A cross-plugin call is an object.") + } + relayed := map[string]any{} + pluginID, ok := object["pluginID"].(string) + if !ok || pluginID == "" { + return nil, invalidCall("pluginID is a non-empty string.") + } + relayed["pluginID"] = pluginID + functionID, ok := object["functionID"].(string) + if !ok || !IsFunctionID(functionID) { + return nil, invalidCall("functionID is a plugin function ID.") + } + relayed["functionID"] = functionID + if params, present := object["params"]; present { + if _, ok := params.(map[string]any); !ok { + return nil, invalidCall("params is an object.") + } + relayed["params"] = params + } + if timeout, present := object["timeoutMilliseconds"]; present { + if milliseconds, ok := unsignedInteger(timeout); !ok || milliseconds == 0 { + return nil, invalidCall("timeoutMilliseconds is a positive integer.") + } + relayed["timeoutMilliseconds"] = timeout + } + if parent, present := object["parentOperationID"]; present { + text, ok := parent.(string) + if !ok || !isParentOperationID(text) { + return nil, invalidCall("parentOperationID is a 1-128 byte string.") + } + relayed["parentOperationID"] = text + } else if serving != "" { + relayed["parentOperationID"] = serving + } + return relayed, nil +} + +// ShowQuickPick: Choose one or more stable item IDs. Permission window.input. +func (w *Window) ShowQuickPick(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodWindowShowQuickPick, context, params) +} + +// ShowInputBox: Request text or a masked password. Permission window.input. +func (w *Window) ShowInputBox(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodWindowShowInputBox, context, params) +} + +// OpenMarkdown: Show a resource or read-only inline Markdown. Permission preview.open. +func (w *Preview) OpenMarkdown(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodPreviewOpenMarkdown, context, params) +} + +// ShowDiff: Compare two read-only inline texts. Permission editor.open. +func (w *Editor) ShowDiff(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodEditorShowDiff, context, params) +} + +// Views provides context-scoped views services. +type Views struct{ host *Host } + +// Views returns native views services. +func (h *Host) Views() *Views { return &Views{host: h} } + +// Refresh: Invalidate a visible owned view instance. Permission views.refresh. +func (w *Views) Refresh(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodViewsRefresh, context, params) +} + +// Output provides context-scoped output services. +type Output struct{ host *Host } + +// Output returns native output services. +func (h *Host) Output() *Output { return &Output{host: h} } + +// Create: Create an independent output channel. Permission output.write. +func (w *Output) Create(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodOutputCreate, context, params) +} + +// Append: Append bounded output text. Permission output.write. +func (w *Output) Append(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodOutputAppend, context, params) +} + +// Clear: Clear an output channel. Permission output.write. +func (w *Output) Clear(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodOutputClear, context, params) +} + +// Show: Show an output channel. Permission output.write. +func (w *Output) Show(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodOutputShow, context, params) +} + +// Dispose: Release an output channel. Permission output.write. +func (w *Output) Dispose(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodOutputDispose, context, params) +} + +// Progress provides context-scoped progress services. +type Progress struct{ host *Host } + +// Progress returns native progress services. +func (h *Host) Progress() *Progress { return &Progress{host: h} } + +// Create: Create cancellable progress. Permission window.progress. +func (w *Progress) Create(context WorkspaceContext, params any) (*Subscription, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + value, err = withContext(context, value) + if err != nil { + return nil, err + } + return w.host.subscribe(methodProgressCreate, value) +} + +// Report: Update progress text or percentage. Permission window.progress. +func (w *Progress) Report(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodProgressReport, context, params) +} + +// End: Release progress. Permission window.progress. +func (w *Progress) End(context WorkspaceContext, params any) (json.RawMessage, error) { + value, err := toValue(params) + if err != nil { + return nil, invalidHostParams() + } + result, err := w.host.scoped(methodProgressEnd, context, value) + if err != nil { + return nil, err + } + object, _ := value.(map[string]any) + id, _ := object["progressID"].(string) + if err := w.host.shared.dispose(id, nil); err != nil { + return nil, err + } + return result, nil +} + +// StatusBar provides context-scoped statusBar services. +type StatusBar struct{ host *Host } + +// StatusBar returns native statusBar services. +func (h *Host) StatusBar() *StatusBar { return &StatusBar{host: h} } + +// SetItem: Create or replace a status item. Permission statusBar.write. +func (w *StatusBar) SetItem(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodStatusBarSetItem, context, params) +} + +// RemoveItem: Remove an owned status item. Permission statusBar.write. +func (w *StatusBar) RemoveItem(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodStatusBarRemoveItem, context, params) +} + +// Clipboard provides context-scoped clipboard services. +type Clipboard struct{ host *Host } + +// Clipboard returns native clipboard services. +func (h *Host) Clipboard() *Clipboard { return &Clipboard{host: h} } + +// ReadText: Read system clipboard text. Permission clipboard.read. +func (w *Clipboard) ReadText(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodClipboardReadText, context, params) +} + +// WriteText: Write system clipboard text. Permission clipboard.write. +func (w *Clipboard) WriteText(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodClipboardWriteText, context, params) +} + +// Reveal: Reveal a saved resource in the file manager. Permission workspace.reveal. +func (w *Workspace) Reveal(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodWorkspaceReveal, context, params) +} + +// Network provides context-scoped network services. +type Network struct{ host *Host } + +// Network returns native network services. +func (h *Host) Network() *Network { return &Network{host: h} } + +// Request: Send a bounded HTTP request with host proxy policy. Permission network.request. +func (w *Network) Request(context WorkspaceContext, params any) (json.RawMessage, error) { + return w.host.scoped(methodNetworkRequest, context, params) +} diff --git a/internal/lithesdk/lithe/protocol.go b/internal/lithesdk/lithe/protocol.go new file mode 100644 index 0000000..b062673 --- /dev/null +++ b/internal/lithesdk/lithe/protocol.go @@ -0,0 +1,355 @@ +package lithe + +import ( + "bytes" + "encoding/json" + "errors" + "math" + "strconv" + "strings" + "unicode/utf8" +) + +// Protocol versions this SDK speaks. +const ( + FunctionsVersion = 0 + LoggingVersion = 0 + KeymapImportVersion = 0 +) + +// JSON-RPC methods of the backend protocol. +const ( + methodInitialize = "initialize" + methodShutdown = "shutdown" + methodExit = "exit" + methodCancelRequest = "$/cancelRequest" + methodLog = "lithe/log" + methodInvoke = "lithe/function/invoke" + methodRegister = "lithe/function/register" + methodUnregister = "lithe/function/unregister" + methodProgress = "lithe/function/progress" + methodKeymapImport = "lithe/keymap/import" + methodKeymapInputs = "lithe/host/keymapImport/listInputs" + methodKeymapChunk = "lithe/host/keymapImport/readChunk" + methodCredentialsGet = "lithe/host/credentials/get" + methodCredentialsSet = "lithe/host/credentials/set" + methodCredentialsDel = "lithe/host/credentials/delete" + methodCapabilities = "lithe/host/getCapabilities" + methodDispose = "lithe/host/subscriptions/dispose" + methodListContexts = "lithe/host/workspace/listContexts" + methodGetContext = "lithe/host/workspace/getContext" + methodGetFolders = "lithe/host/workspace/getFolders" + methodGetHostPaths = "lithe/host/workspace/getHostPaths" + methodReadDirectory = "lithe/host/workspace/readDirectory" + methodStat = "lithe/host/workspace/stat" + methodReadFile = "lithe/host/workspace/readFile" + methodWatch = "lithe/host/workspace/watch" + methodFindFiles = "lithe/host/workspace/findFiles" + methodFindText = "lithe/host/workspace/findText" + methodCreate = "lithe/host/workspace/create" + methodRename = "lithe/host/workspace/rename" + methodCopy = "lithe/host/workspace/copy" + methodTrash = "lithe/host/workspace/trash" + methodDocumentsList = "lithe/host/documents/list" + methodDocumentsSnap = "lithe/host/documents/getSnapshot" + methodDocumentsSave = "lithe/host/documents/save" + methodDocumentsAs = "lithe/host/documents/saveAs" + methodDocumentsClose = "lithe/host/documents/close" + methodEditorActions = "lithe/host/editor/registerActions" + methodEditorActive = "lithe/host/editor/getActive" + methodEditorSelect = "lithe/host/editor/getSelections" + methodEditorApply = "lithe/host/editor/applyEdits" + methodEditorReplace = "lithe/host/editor/replaceSelections" + methodEditorInsert = "lithe/host/editor/insertText" + methodEditorOpen = "lithe/host/editor/open" + methodEditorReveal = "lithe/host/editor/reveal" + methodWindowShowQuickPick = "lithe/host/window/showQuickPick" + methodWindowShowInputBox = "lithe/host/window/showInputBox" + methodPreviewOpenMarkdown = "lithe/host/preview/openMarkdown" + methodEditorShowDiff = "lithe/host/editor/showDiff" + methodViewsRefresh = "lithe/host/views/refresh" + methodOutputCreate = "lithe/host/output/create" + methodOutputAppend = "lithe/host/output/append" + methodOutputClear = "lithe/host/output/clear" + methodOutputShow = "lithe/host/output/show" + methodOutputDispose = "lithe/host/output/dispose" + methodProgressCreate = "lithe/host/progress/create" + methodProgressReport = "lithe/host/progress/report" + methodProgressEnd = "lithe/host/progress/end" + methodStatusBarSetItem = "lithe/host/statusBar/setItem" + methodStatusBarRemoveItem = "lithe/host/statusBar/removeItem" + methodClipboardReadText = "lithe/host/clipboard/readText" + methodClipboardWriteText = "lithe/host/clipboard/writeText" + methodWorkspaceReveal = "lithe/host/workspace/reveal" + methodNetworkRequest = "lithe/host/network/request" + methodPreviewHTML = "lithe/host/preview/openHTML" + methodBrowserOpen = "lithe/host/browser/openExternal" + methodShowInfo = "lithe/host/window/showInformation" + methodShowWarning = "lithe/host/window/showWarning" + methodShowError = "lithe/host/window/showError" + methodTerminalCreate = "lithe/host/terminal/create" + methodTerminalShow = "lithe/host/terminal/show" + methodTerminalClose = "lithe/host/terminal/close" + methodTerminalReopen = "lithe/host/terminal/reopen" + methodTerminalDrop = "lithe/host/terminal/dispose" + methodTerminalExit = "lithe/host/terminal/onExit" + methodProviders = "lithe/host/functions/providers" + methodRelayInvoke = "lithe/host/functions/invoke" + methodContexts = "lithe/host/workspace/didChangeContexts" + methodNotify = "lithe/host/subscriptions/notify" + methodCommandRan = "lithe/host/commands/didRun" + hostPrefix = "lithe/host/" +) + +// JSON-RPC error numbers. +const ( + rpcParseError = -32700 + rpcInvalidRequest = -32600 + rpcMethodNotFound = -32601 + rpcInvalidParams = -32602 + rpcInternalError = -32603 + rpcServerNotInitialized = -32002 + rpcRequestFailed = -32000 + rpcRequestCancelled = -32800 +) + +// Protocol limits. +const ( + MaxFunctions = 256 + maxFunctionIDBytes = 128 + maxPluginErrorCode = 64 + maxErrorMessageBytes = 1024 + maxResultBytes = 1 << 20 + maxCredentialKeyBytes = 128 + maxSecretBytes = 16 << 10 + maxPendingHostCalls = 16 + maxEarlyEvents = 128 + maxCommandIDBytes = 128 + maxParentOperation = 128 + maxHostPathRoots = 256 + maxSafeInteger = 1<<53 - 1 +) + +// IsFunctionID reports whether id is dot-separated lowerCamelCase segments +// of at most 128 bytes, the form of a plugin function ID. +func IsFunctionID(id string) bool { + if id == "" || len(id) > maxFunctionIDBytes { + return false + } + for _, segment := range strings.Split(id, ".") { + if segment == "" || segment[0] < 'a' || segment[0] > 'z' { + return false + } + for i := 1; i < len(segment); i++ { + if !isASCIIAlnum(segment[i]) { + return false + } + } + } + return true +} + +// IsPluginErrorCode reports whether code can name a plugin error: a letter, +// then letters, digits, ".", "_" or "-", at most 64 bytes. +func IsPluginErrorCode(code string) bool { + if code == "" || len(code) > maxPluginErrorCode || !isASCIILetter(code[0]) { + return false + } + for i := 1; i < len(code); i++ { + if !isASCIIAlnum(code[i]) && !strings.ContainsRune("._-", rune(code[i])) { + return false + } + } + return true +} + +// IsCredentialKey reports whether key is 1-128 ASCII letters, digits, ".", +// "_", ":" or "-". Context and subscription IDs use the same form. +func IsCredentialKey(key string) bool { + if key == "" || len(key) > maxCredentialKeyBytes { + return false + } + for i := 0; i < len(key); i++ { + if !isASCIIAlnum(key[i]) && !strings.ContainsRune("._:-", rune(key[i])) { + return false + } + } + return true +} + +// IsCommandID reports whether id is 1-128 lowercase letters, digits, "." or +// "-", the form of a contributed command. +func IsCommandID(id string) bool { + if id == "" || len(id) > maxCommandIDBytes { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !(c >= 'a' && c <= 'z') && !(c >= '0' && c <= '9') && c != '.' && c != '-' { + return false + } + } + return true +} + +// isParentOperationID reports whether id can name the call a cross-plugin +// call belongs to: 1-128 bytes. +func isParentOperationID(id string) bool { + return id != "" && len(id) <= maxParentOperation +} + +func isASCIILetter(c byte) bool { return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' } + +func isASCIIAlnum(c byte) bool { return isASCIILetter(c) || c >= '0' && c <= '9' } + +// offers reports whether a capability offer lists protocol version exactly. +func offers(offer any, version int64) bool { + object, ok := offer.(map[string]any) + if !ok { + return false + } + versions, ok := object["versions"].([]any) + if !ok { + return false + } + for _, value := range versions { + if number, ok := value.(json.Number); ok { + if parsed, err := strconv.ParseInt(string(number), 10, 64); err == nil && parsed == version { + return true + } + } + } + return false +} + +// generation reads a positive safe integer; 2 and 2.0 both count. +func generation(value any) (uint64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + text := string(number) + var parsed uint64 + if unsigned, err := strconv.ParseUint(text, 10, 64); err == nil { + parsed = unsigned + } else if strings.ContainsAny(text, ".eE") { + float, err := strconv.ParseFloat(text, 64) + if err != nil || float < 1 || float > maxSafeInteger || float != math.Trunc(float) { + return 0, false + } + parsed = uint64(float) + } else { + return 0, false + } + if parsed < 1 || parsed > maxSafeInteger { + return 0, false + } + return parsed, true +} + +// unsignedInteger reads a non-negative JSON integer. +func unsignedInteger(value any) (uint64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseUint(string(number), 10, 64) + return parsed, err == nil +} + +// integer reads a JSON integer that fits in int64. +func integer(value any) (int64, bool) { + number, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseInt(string(number), 10, 64) + return parsed, err == nil +} + +var errTrailingData = errors.New("trailing data after the JSON value") + +// boundedText cuts text to at most limit bytes on a character boundary. +func boundedText(text string, limit int) string { + if len(text) <= limit { + return text + } + end := limit + for end > 0 && !utf8.RuneStart(text[end]) { + end-- + } + return text[:end] +} + +// decodeJSON parses JSON keeping numbers exact. +func decodeJSON(data []byte) (any, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value any + if err := decoder.Decode(&value); err != nil { + return nil, err + } + if decoder.More() { + return nil, errTrailingData + } + return value, nil +} + +// encodeJSON serializes value as compact JSON without HTML escaping, the +// bytes the host receives. +func encodeJSON(value any) ([]byte, error) { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetEscapeHTML(false) + if err := encoder.Encode(value); err != nil { + return nil, err + } + return bytes.TrimSuffix(buffer.Bytes(), []byte("\n")), nil +} + +// raw serializes a decoded value for a caller that unmarshals it. +func raw(value any) json.RawMessage { + data, err := encodeJSON(value) + if err != nil { + return json.RawMessage("null") + } + return data +} + +// toValue converts any JSON-serializable Go value into the SDK's dynamic +// form -- map[string]any, []any, string, json.Number, bool and nil -- by +// encoding and decoding it, so nested numbers are exact too. +func toValue(value any) (any, error) { + if value == nil { + return nil, nil + } + data, err := encodeJSON(value) + if err != nil { + return nil, err + } + return decodeJSON(data) +} + +// field is value[key] when value is an object, else nil. +func field(value any, key string) any { + object, _ := value.(map[string]any) + return object[key] +} + +// pointer follows keys through nested objects. +func pointer(value any, keys ...string) any { + for _, key := range keys { + value = field(value, key) + } + return value +} + +// requestKey is a JSON-RPC ID as a map key; numbers and strings never +// collide. +func requestKey(id any) string { + data, err := encodeJSON(id) + if err != nil { + return "null" + } + return string(data) +} diff --git a/internal/lithesdk/lithe/stdio_dup2.go b/internal/lithesdk/lithe/stdio_dup2.go new file mode 100644 index 0000000..07dec51 --- /dev/null +++ b/internal/lithesdk/lithe/stdio_dup2.go @@ -0,0 +1,30 @@ +//go:build darwin || dragonfly || freebsd || netbsd || openbsd + +package lithe + +import ( + "io" + "os" + "syscall" +) + +// protocolOutput is the stream the protocol is written to: a duplicate of +// the original stdout descriptor, with descriptor 1 pointed at stderr, so +// output printed by plugin code, its dependencies or the processes it starts +// cannot corrupt the protocol. The duplicate is close-on-exec, so child +// processes do not hold the protocol pipe open. +func protocolOutput() io.Writer { + syscall.ForkLock.RLock() + protocol, err := syscall.Dup(1) + if err == nil { + syscall.CloseOnExec(protocol) + } + syscall.ForkLock.RUnlock() + if err != nil { + return os.Stdout + } + if err := syscall.Dup2(2, 1); err != nil { + os.Exit(1) + } + return os.NewFile(uintptr(protocol), "lithe-protocol") +} diff --git a/internal/lithesdk/lithe/stdio_linux.go b/internal/lithesdk/lithe/stdio_linux.go new file mode 100644 index 0000000..90d8b49 --- /dev/null +++ b/internal/lithesdk/lithe/stdio_linux.go @@ -0,0 +1,31 @@ +//go:build linux + +package lithe + +import ( + "io" + "os" + "syscall" +) + +// protocolOutput is the stream the protocol is written to: a duplicate of +// the original stdout descriptor, with descriptor 1 pointed at stderr, so +// output printed by plugin code, its dependencies or the processes it starts +// cannot corrupt the protocol. The duplicate is close-on-exec, so child +// processes do not hold the protocol pipe open. +func protocolOutput() io.Writer { + syscall.ForkLock.RLock() + protocol, err := syscall.Dup(1) + if err == nil { + syscall.CloseOnExec(protocol) + } + syscall.ForkLock.RUnlock() + if err != nil { + return os.Stdout + } + // linux/arm64 has no dup2; dup3 with no flags is the same. + if err := syscall.Dup3(2, 1, 0); err != nil { + os.Exit(1) + } + return os.NewFile(uintptr(protocol), "lithe-protocol") +} diff --git a/internal/lithesdk/lithe/stdio_other.go b/internal/lithesdk/lithe/stdio_other.go new file mode 100644 index 0000000..4c5d3ce --- /dev/null +++ b/internal/lithesdk/lithe/stdio_other.go @@ -0,0 +1,13 @@ +//go:build !linux && !darwin && !dragonfly && !freebsd && !netbsd && !openbsd + +package lithe + +import ( + "io" + "os" +) + +// protocolOutput is the stream the protocol is written to: stdout itself. +// Here descriptor 1 cannot be redirected, so plugin code must not print to +// stdout; write to stderr or record diagnostics instead. +func protocolOutput() io.Writer { return os.Stdout } diff --git a/internal/lithesdk/lithe/view.go b/internal/lithesdk/lithe/view.go new file mode 100644 index 0000000..322ddd7 --- /dev/null +++ b/internal/lithesdk/lithe/view.go @@ -0,0 +1,343 @@ +package lithe + +import ( + "encoding/json" + "maps" + "strconv" +) + +// Plugin views: the event a view function receives and the result it +// returns. A tool window or settings region names a view function in +// view.function (contract v1, "Plugin views"). Declare it with +// [Backend.View]: the SDK reads the params into a [ViewEvent] and answers +// the handler's [ViewResult]. View and canvas nodes are JSON values -- maps, +// structs, or json.RawMessage -- shaped as plugin-ui.schema.json describes; +// Core checks every result before the host draws it. + +const codeInvalidViewEvent = "sdk.view.invalidEvent" + +// ViewEventKind is why the host called the view function. +type ViewEventKind string + +const ( + // ViewOpen: the view became visible; answer a whole view. + ViewOpen ViewEventKind = "open" + // ViewClose: the view went away; the result is ignored. + ViewClose ViewEventKind = "close" + ViewClick ViewEventKind = "click" + ViewChange ViewEventKind = "change" + ViewSelect ViewEventKind = "select" + ViewActivate ViewEventKind = "activate" + ViewViewport ViewEventKind = "viewport" + // ViewResize: the view's width stopped changing, for a view with a + // canvas whose on lists resize; ViewEvent.Width is the new width. + ViewResize ViewEventKind = "resize" + // ViewSettings: the effective or draft setting values changed. + ViewSettings ViewEventKind = "settings" + ViewRefresh ViewEventKind = "refresh" + ViewExpand ViewEventKind = "expand" + ViewLoadMore ViewEventKind = "loadMore" +) + +func parseViewEventKind(name string) (ViewEventKind, bool) { + switch kind := ViewEventKind(name); kind { + case ViewOpen, ViewClose, ViewClick, ViewChange, ViewSelect, ViewActivate, ViewViewport, ViewResize, ViewSettings, ViewRefresh, ViewExpand, ViewLoadMore: + return kind, true + } + return "", false +} + +// SurfaceKind is the kind of declaration being drawn. +type SurfaceKind string + +const ( + SurfaceToolWindow SurfaceKind = "toolWindow" + SurfaceSettingRegion SurfaceKind = "settingRegion" +) + +// ViewSurface is the declaration being drawn: a tool window or a settings +// region, by its ID. +type ViewSurface struct { + Kind SurfaceKind + ID string +} + +// Viewport is the visible part of a canvas, in view-box coordinates. +type Viewport struct { + X, Y, Width, Height float64 +} + +// ViewEvent is the params of one call to a view function. An optional +// string field is "" when the host did not send it. +type ViewEvent struct { + Kind ViewEventKind + // Instance is host-chosen; each ViewOpen starts a new instance. + Instance string + Surface ViewSurface + // Language is the interface language tag, such as en or zh-Hans; + // return view text in it. + Language string + // Effective holds the saved setting values in force, by setting ID. + Effective map[string]any + // Draft holds values changed in the open settings window but not + // applied; empty in a tool window. + Draft map[string]any + // Node is the node acted on: the group inside a canvas, the tree for an + // item. + Node string + // Canvas is the canvas ID of a click inside a canvas and of a viewport + // event. + Canvas string + // Value is a change's value: a string, a bool for a toggle, or the bound + // setting's new draft value (a json.Number for a number); nil when + // absent. + Value any + // Setting is the setting ID of a change of a control bound to one. + Setting string + // Item is the tree item ID of a select or activate event. + Item string + // Cursor is the opaque continuation of a tree loadMore event. + Cursor string + Viewport *Viewport + // Width is the width in points the host lays the view out in, on every + // event from a host that reports it. List resize in a canvas's on only + // when it is present: a host without it may refuse the canvas. + Width *float64 +} + +// ParseViewEvent reads the params the host sent; it fails with +// sdk.view.invalidEvent when a required field is missing or a field has the +// wrong type. An optional field that is null counts as absent. +func ParseViewEvent(params json.RawMessage) (*ViewEvent, error) { + value, err := decodeJSON(params) + if err != nil { + return nil, invalidViewEvent() + } + return parseViewEvent(value) +} + +func invalidViewEvent() *SdkError { + return newSdkError(codeInvalidViewEvent, "Invalid view event.") +} + +// optionalString reads fields[key]: absent or null is "", a string is +// itself, and anything else is invalid. +func optionalString(fields map[string]any, key string) (string, bool, error) { + switch value := fields[key].(type) { + case nil: + return "", false, nil + case string: + return value, true, nil + default: + return "", false, invalidViewEvent() + } +} + +func number(value any) (float64, bool) { + text, ok := value.(json.Number) + if !ok { + return 0, false + } + parsed, err := strconv.ParseFloat(string(text), 64) + return parsed, err == nil +} + +func parseViewEvent(params any) (*ViewEvent, error) { + object, ok := params.(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + name, _ := object["event"].(string) + kind, ok := parseViewEventKind(name) + if !ok { + return nil, invalidViewEvent() + } + surfaceFields, ok := object["surface"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + toolWindow, isToolWindow, err := optionalString(surfaceFields, "toolWindowID") + if err != nil { + return nil, err + } + region, isRegion, err := optionalString(surfaceFields, "settingRegionID") + if err != nil { + return nil, err + } + var surface ViewSurface + switch { + case isToolWindow && !isRegion: + surface = ViewSurface{SurfaceToolWindow, toolWindow} + case isRegion && !isToolWindow: + surface = ViewSurface{SurfaceSettingRegion, region} + default: + return nil, invalidViewEvent() + } + settings, ok := object["settings"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + effective, ok := settings["effective"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + draft, ok := settings["draft"].(map[string]any) + if !ok { + return nil, invalidViewEvent() + } + event := &ViewEvent{Kind: kind, Surface: surface, Effective: maps.Clone(effective), Draft: maps.Clone(draft)} + if event.Instance, ok = object["instance"].(string); !ok { + return nil, invalidViewEvent() + } + if event.Language, ok = object["language"].(string); !ok { + return nil, invalidViewEvent() + } + switch viewport := object["viewport"].(type) { + case nil: + case map[string]any: + var fields [4]float64 + for i, key := range []string{"x", "y", "width", "height"} { + if fields[i], ok = number(viewport[key]); !ok { + return nil, invalidViewEvent() + } + } + event.Viewport = &Viewport{fields[0], fields[1], fields[2], fields[3]} + default: + return nil, invalidViewEvent() + } + if width, present := object["width"]; present && width != nil { + parsed, ok := number(width) + if !ok { + return nil, invalidViewEvent() + } + event.Width = &parsed + } + switch value := object["value"].(type) { + case nil: + case string, bool, json.Number: + event.Value = value + default: + return nil, invalidViewEvent() + } + for key, target := range map[string]*string{"node": &event.Node, "canvas": &event.Canvas, "setting": &event.Setting, "item": &event.Item, "cursor": &event.Cursor} { + if *target, _, err = optionalString(object, key); err != nil { + return nil, err + } + } + return event, nil +} + +// ViewResult is what a view function answers. The first result after +// ViewOpen is a whole view. The zero value is [Unchanged]. +type ViewResult struct { + kind resultKind + nodes []any + patches []Patch +} + +type resultKind int + +const ( + resultUnchanged resultKind = iota + resultView + resultPatches +) + +// View answers the whole view: its nodes, top to bottom. +func View(nodes ...any) ViewResult { + return ViewResult{kind: resultView, nodes: nodes} +} + +// Patches answers edits to the view the host is drawing, applied in order. +func Patches(patches ...Patch) ViewResult { + return ViewResult{kind: resultPatches, patches: patches} +} + +// Unchanged answers that nothing changed. +func Unchanged() ViewResult { return ViewResult{} } + +// MarshalJSON writes {"view": [...]}, {"patches": [...]}, or {}. +func (r ViewResult) MarshalJSON() ([]byte, error) { + switch r.kind { + case resultView: + nodes := r.nodes + if nodes == nil { + nodes = []any{} + } + return encodeJSON(map[string]any{"view": nodes}) + case resultPatches: + patches := r.patches + if patches == nil { + patches = []Patch{} + } + return encodeJSON(map[string]any{"patches": patches}) + default: + return []byte("{}"), nil + } +} + +// Patch is one edit, addressed by node ID within the host controls, or +// within one canvas scene ([Patch.InCanvas]) or one tree's items +// ([Patch.InTree]). Each method returns a new patch. +type Patch struct { + fields map[string]any +} + +func newPatch(op, id string, hasID bool) Patch { + fields := map[string]any{"op": op} + if hasID { + fields["id"] = id + } + return Patch{fields} +} + +func (p Patch) with(key string, value any) Patch { + fields := maps.Clone(p.fields) + if fields == nil { + fields = map[string]any{} + } + fields[key] = value + return Patch{fields} +} + +// PatchSet merges fields, a JSON object, into the node; a null field +// removes it. +func PatchSet(id string, fields any) Patch { + return newPatch("set", id, true).with("fields", fields) +} + +// PatchReplace swaps the node, with its subtree, for node. +func PatchReplace(id string, node any) Patch { + return newPatch("replace", id, true).with("node", node) +} + +// PatchRemove deletes the node and its subtree. +func PatchRemove(id string) Patch { + return newPatch("remove", id, true) +} + +// PatchInsert adds node at the end of the top level; see [Patch.Under] and +// [Patch.At]. +func PatchInsert(node any) Patch { + return newPatch("insert", "", false).with("node", node) +} + +// Under makes an insert go into the children of parent. +func (p Patch) Under(parent string) Patch { return p.with("parent", parent) } + +// At makes an insert go at index instead of the end. +func (p Patch) At(index int) Patch { return p.with("index", index) } + +// InCanvas addresses the nodes of canvas canvas. +func (p Patch) InCanvas(canvas string) Patch { return p.with("canvas", canvas) } + +// InTree addresses the items of tree tree. +func (p Patch) InTree(tree string) Patch { return p.with("tree", tree) } + +// MarshalJSON writes the patch object. +func (p Patch) MarshalJSON() ([]byte, error) { + if p.fields == nil { + return []byte("{}"), nil + } + return encodeJSON(p.fields) +} diff --git a/internal/lsp/server.go b/internal/lsp/server.go index 685004f..0f7aa01 100644 --- a/internal/lsp/server.go +++ b/internal/lsp/server.go @@ -153,10 +153,16 @@ func (s *Server) dispatch(m *message) { s.cancel(m.Params) case "textDocument/definition": s.query(m, s.definition) + case "textDocument/implementation": + s.query(m, s.implementations) case "textDocument/references": s.query(m, s.references) case "textDocument/documentSymbol": s.query(m, s.documentSymbol) + case "javaNavigation/superDeclarations": + s.query(m, s.superDeclarations) + case "javaNavigation/markers": + s.query(m, s.navigationMarkers) default: if m.isRequest() { s.conn.replyError(m.ID, codeMethodNotFound, "method not supported: "+m.Method) @@ -296,6 +302,7 @@ func (s *Server) initialize(params json.RawMessage) any { "change": 2, // incremental }, "definitionProvider": true, + "implementationProvider": true, "referencesProvider": true, "documentSymbolProvider": true, "workspace": map[string]any{ @@ -535,6 +542,118 @@ func (s *Server) definition(params json.RawMessage) (func(context.Context) (any, }, nil } +func (s *Server) implementations(params json.RawMessage) (func(context.Context) (any, error), error) { + return s.positionTargets(params, func(ctx context.Context, w *workspace.Workspace, doc workspace.Doc, text []byte, off int) ([]workspace.Target, error) { + return w.Implementations(ctx, doc, text, off) + }) +} + +func (s *Server) superDeclarations(params json.RawMessage) (func(context.Context) (any, error), error) { + return s.positionTargets(params, func(ctx context.Context, w *workspace.Workspace, doc workspace.Doc, text []byte, off int) ([]workspace.Target, error) { + return w.SuperDeclarations(ctx, doc, text, off) + }) +} + +func (s *Server) positionTargets( + params json.RawMessage, + query func(ctx context.Context, w *workspace.Workspace, doc workspace.Doc, text []byte, off int) ([]workspace.Target, error), +) (func(context.Context) (any, error), error) { + var p textDocumentPosition + if err := json.Unmarshal(params, &p); err != nil { + return nil, err + } + w, doc, text, off, err := s.prepare(p) + if err != nil { + return nil, err + } + return func(ctx context.Context) (any, error) { + out := []Location{} + if w == nil || !doc.Covered() { + return out, nil + } + targets, err := query(ctx, w, doc, text, off) + if err != nil { + return nil, err + } + texts := map[string][]byte{} + for _, t := range targets { + loc, err := s.locationCached(w, t, texts) + if err != nil { + continue + } + out = append(out, loc) + } + return out, nil + }, nil +} + +type markerTargetJSON struct { + Name string `json:"name"` + Location Location `json:"location"` +} + +type markerJSON struct { + Line int `json:"line"` + Character int `json:"character"` + EndCharacter int `json:"endCharacter"` + Direction string `json:"direction"` + Relation string `json:"relation"` + Targets []markerTargetJSON `json:"targets"` +} + +func (s *Server) navigationMarkers(params json.RawMessage) (func(context.Context) (any, error), error) { + var p struct { + TextDocument textDocumentIdentifier `json:"textDocument"` + Text string `json:"text"` + } + if err := json.Unmarshal(params, &p); err != nil { + return nil, err + } + path, text, err := s.snapshot(p.TextDocument.URI) + if err != nil { + return nil, err + } + if p.Text != "" { + text = []byte(p.Text) + } + w, doc := s.locate(path) + enc := s.encoding() + return func(ctx context.Context) (any, error) { + if w == nil || !doc.Covered() || !codenav.Supports(path) { + return map[string]any{"markers": []markerJSON{}}, nil + } + markers, err := w.NavigationMarkers(ctx, doc, text) + if err != nil { + return nil, err + } + texts := map[string][]byte{} + out := make([]markerJSON, 0, len(markers)) + for _, m := range markers { + r := nameRange(text, m.Line, m.Column, enc) + targets := make([]markerTargetJSON, 0, len(m.Targets)) + for _, mt := range m.Targets { + loc, err := s.locationCached(w, mt.Target, texts) + if err != nil { + continue + } + targets = append(targets, markerTargetJSON{Name: mt.Name, Location: loc}) + } + if len(targets) == 0 { + continue + } + out = append(out, markerJSON{ + Line: r.Start.Line, + Character: r.Start.Character, + EndCharacter: r.End.Character, + Direction: m.Direction, + Relation: m.Relation, + Targets: targets, + }) + } + return map[string]any{"markers": out}, nil + }, nil +} + func (s *Server) references(params json.RawMessage) (func(context.Context) (any, error), error) { var p struct { textDocumentPosition diff --git a/internal/lsp/server_test.go b/internal/lsp/server_test.go index 74a75ae..e08252f 100644 --- a/internal/lsp/server_test.go +++ b/internal/lsp/server_test.go @@ -161,16 +161,17 @@ public class Circle implements Shape { var init struct { Capabilities struct { - PositionEncoding string `json:"positionEncoding"` - DefinitionProvider bool `json:"definitionProvider"` - ReferencesProvider bool `json:"referencesProvider"` + PositionEncoding string `json:"positionEncoding"` + DefinitionProvider bool `json:"definitionProvider"` + ImplementationProvider bool `json:"implementationProvider"` + ReferencesProvider bool `json:"referencesProvider"` } `json:"capabilities"` } c.call("initialize", map[string]any{ "processId": nil, "rootUri": uriOf(root), "capabilities": map[string]any{"textDocument": map[string]any{"documentSymbol": map[string]any{"hierarchicalDocumentSymbolSupport": true}}}, }, &init) - if init.Capabilities.PositionEncoding != "utf-16" || !init.Capabilities.DefinitionProvider || !init.Capabilities.ReferencesProvider { + if init.Capabilities.PositionEncoding != "utf-16" || !init.Capabilities.DefinitionProvider || !init.Capabilities.ImplementationProvider || !init.Capabilities.ReferencesProvider { t.Fatalf("capabilities = %+v", init.Capabilities) } c.notify("initialized", map[string]any{}) @@ -235,6 +236,47 @@ public class Circle implements Shape { t.Errorf("outline = %s, want %s", got, want) } + // Implementations from Shape.area() and superDeclarations from Circle.area(). + circleURI := uriOf(filepath.Join(root, "src/a/Circle.java")) + var impls []Location + c.call("textDocument/implementation", map[string]any{ + "textDocument": map[string]any{"uri": shapeURI}, "position": Position{3, 12}, + }, &impls) + if len(impls) != 1 || impls[0].URI != circleURI || impls[0].Range.Start.Line != 8 { + t.Errorf("implementations of Shape.area = %+v, want Circle.area on line 8", impls) + } + + var supers []Location + c.call("javaNavigation/superDeclarations", map[string]any{ + "textDocument": map[string]any{"uri": circleURI}, "position": Position{8, 18}, + }, &supers) + if len(supers) != 1 || supers[0].URI != shapeURI || supers[0].Range.Start.Line != 3 { + t.Errorf("superDeclarations of Circle.area = %+v, want Shape.area on line 3", supers) + } + + var markerResp struct { + Markers []struct { + Line int `json:"line"` + Direction string `json:"direction"` + Relation string `json:"relation"` + Targets []struct { + Name string `json:"name"` + Location Location `json:"location"` + } `json:"targets"` + } `json:"markers"` + } + c.call("javaNavigation/markers", map[string]any{ + "textDocument": map[string]any{"uri": circleURI}, + }, &markerResp) + if len(markerResp.Markers) != 2 { + t.Errorf("Circle navigation markers = %+v, want 2 (class up + area up)", markerResp.Markers) + } + for _, m := range markerResp.Markers { + if m.Direction != "up" || m.Relation != "interface" { + t.Errorf("Circle marker = %+v, want up/interface", m) + } + } + // An unsupported request is refused, not ignored. c.nextID++ c.send(map[string]any{"jsonrpc": "2.0", "id": c.nextID, "method": "textDocument/hover", "params": map[string]any{}}) diff --git a/internal/workspace/workspace.go b/internal/workspace/workspace.go index 19523ba..63ea6ee 100644 --- a/internal/workspace/workspace.go +++ b/internal/workspace/workspace.go @@ -247,6 +247,103 @@ func (w *Workspace) Definition(ctx context.Context, d Doc, text []byte, off int) return t, true, nil } +// MarkerTarget pairs a display name with a resolved workspace or library Target. +type MarkerTarget struct { + Name string + Target Target +} + +// Marker describes one bidirectional inheritance or implementation gutter icon. +type Marker struct { + Line int + Column int + Direction string + Relation string + Targets []MarkerTarget +} + +// Implementations returns all subtypes or overriding/implementing methods for +// the symbol at byte offset off of text, the editor's content of d. +func (w *Workspace) Implementations(ctx context.Context, d Doc, text []byte, off int) ([]Target, error) { + return w.resolveLocationList(ctx, d, text, off, w.ix.LibraryImplementations, w.ix.Implementations) +} + +// SuperDeclarations returns direct supertype or ancestor method declarations +// for the symbol at byte offset off of text, the editor's content of d. +func (w *Workspace) SuperDeclarations(ctx context.Context, d Doc, text []byte, off int) ([]Target, error) { + return w.resolveLocationList(ctx, d, text, off, w.ix.LibrarySuperDeclarations, w.ix.SuperDeclarations) +} + +func (w *Workspace) resolveLocationList( + ctx context.Context, + d Doc, + text []byte, + off int, + libFn, wsFn func(string, []byte, int) []codenav.Location, +) ([]Target, error) { + if !d.Covered() { + return nil, nil + } + if err := w.ensure(ctx); err != nil { + return nil, err + } + var locs []codenav.Location + if d.Library != "" { + locs = libFn(d.Library, text, off) + } else { + locs = wsFn(d.Rel, text, off) + } + out := make([]Target, 0, len(locs)) + for _, l := range locs { + t, err := w.target(l) + if err != nil { + continue + } + out = append(out, t) + } + return out, nil +} + +// NavigationMarkers returns verified bidirectional inheritance/implementation +// gutter markers for d. +func (w *Workspace) NavigationMarkers(ctx context.Context, d Doc, text []byte) ([]Marker, error) { + if !d.Covered() { + return nil, nil + } + if err := w.ensure(ctx); err != nil { + return nil, err + } + var raw []codenav.NavMarker + if d.Library != "" { + raw = w.ix.LibraryNavigationMarkers(d.Library, text) + } else { + raw = w.ix.NavigationMarkers(d.Rel, text) + } + out := make([]Marker, 0, len(raw)) + for _, m := range raw { + targets := make([]MarkerTarget, 0, len(m.Targets)) + for _, mt := range m.Targets { + t, err := w.target(mt.Location) + if err != nil { + continue + } + targets = append(targets, MarkerTarget{Name: mt.Name, Target: t}) + } + if len(targets) == 0 { + continue + } + out = append(out, Marker{ + Line: m.Line, + Column: m.Column, + Direction: m.Direction, + Relation: m.Relation, + Targets: targets, + }) + } + return out, nil +} + + // References lists the places that refer to the declaration named at byte // offset off of text, the editor's content of d, in path, line and column // order; with decl set the declaration itself comes first. Only occurrences diff --git a/io.github.lithe-idea.java-navigation/plugin.json b/io.github.lithe-idea.java-navigation/plugin.json index f571d1d..25f6c2a 100644 --- a/io.github.lithe-idea.java-navigation/plugin.json +++ b/io.github.lithe-idea.java-navigation/plugin.json @@ -2,9 +2,10 @@ "schemaVersion": 0, "id": "io.github.lithe-idea.java-navigation", "displayName": "Java Support Lite", - "version": "0.1.0", + "version": "0.2.0", "pluginAPIVersion": 0, "requires": { + "backend": 0, "languageServers": 0, "languages": 0 }, @@ -14,10 +15,15 @@ "signatureRequirement": "none" }, "permissions": [ - "languageServer.launch" + "backend.launch", + "editor.actions", + "languageServer.launch", + "languageServer.request", + "workspace.metadata" ], "activationEvents": [ - "onLanguage:java" + "onLanguage:java", + "onWorkspaceOpen" ], "languages": [ { @@ -49,7 +55,21 @@ ], "validationArguments": [ "--version" + ], + "requestMethods": [ + "textDocument/implementation", + "javaNavigation/superDeclarations", + "javaNavigation/markers" ] } - ] + ], + "backend": { + "launch": { + "kind": "packaged", + "path": "bin/java-navigation" + }, + "arguments": [ + "--backend" + ] + } } diff --git a/scripts/package.mjs b/scripts/package.mjs index 18bbcbf..0616266 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -29,7 +29,7 @@ const TARGETS = [ { platform: "windows-arm64", goos: "windows", goarch: "arm64" }, ]; // Files copied next to plugin.json in every archive. -const INCLUDED = ["LICENSE", "THIRD_PARTY_NOTICES.md"]; +const INCLUDED = ["LICENSE", "THIRD_PARTY_NOTICES.md", "vendor/LICENSE"]; const manifest = JSON.parse(readFileSync(`${PACKAGE_DIR}/plugin.json`, "utf8")); const problems = []; @@ -41,6 +41,10 @@ const servers = manifest.languageServers ?? []; if (servers.length !== 1 || servers[0].launch?.kind !== "packaged" || servers[0].launch?.path !== `bin/${BINARY}`) { problems.push(`plugin.json must declare one packaged language server at bin/${BINARY}`); } +const backend = manifest.backend; +if (backend?.launch?.kind !== "packaged" || backend?.launch?.path !== `bin/${BINARY}`) { + problems.push(`plugin.json must declare a packaged backend at bin/${BINARY}`); +} const tagFlag = process.argv.indexOf("--expect-tag"); if (tagFlag >= 0) { @@ -73,8 +77,13 @@ for (const target of targets) { chmodSync(join(pkg, "bin", exe), 0o755); const platformManifest = structuredClone(manifest); platformManifest.languageServers[0].launch.path = `bin/${exe}`; + platformManifest.backend.launch.path = `bin/${exe}`; writeFileSync(join(pkg, "plugin.json"), `${JSON.stringify(platformManifest, null, 2)}\n`); - for (const file of INCLUDED) copyFileSync(file, join(pkg, file)); + for (const file of INCLUDED) { + const dest = join(pkg, file); + mkdirSync(join(dest, ".."), { recursive: true }); + copyFileSync(file, dest); + } const name = `${ASSET_PREFIX}-${manifest.version}-${target.platform}.zip`; const asset = resolve("dist", name); diff --git a/sdk.lock.json b/sdk.lock.json new file mode 100644 index 0000000..6b69f03 --- /dev/null +++ b/sdk.lock.json @@ -0,0 +1,69 @@ +{ + "schemaVersion": 1, + "source": { + "repository": "https://github.com/Lithe-IDEA/Lithe-core-rust", + "revision": "0d79e17fde389f559bcb3eeeb11baace13895576" + }, + "files": [ + { + "upstream": "shared/plugins/LICENSE", + "path": "vendor/LICENSE", + "sha256": "93ff573f89d32394501fcc82767e73b1824add861f088bbd3eec9e0afae20d21" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/backend.go", + "path": "internal/lithesdk/lithe/backend.go", + "sha256": "4a1c2c4d68cac20f93312c58f63b49615cdf05f3d6061f9330a7dcb18fe4f38e" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/cancellation.go", + "path": "internal/lithesdk/lithe/cancellation.go", + "sha256": "bb6f16abf2ce8b0405f0b7fd9a4621d6c1293e6ec0bfab5313b219b37b0856b8" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/diagnostics.go", + "path": "internal/lithesdk/lithe/diagnostics.go", + "sha256": "dc17212a6af0c7236860480b9e97e49d31ade1d741d021eea04a297f552dca9b" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/errors.go", + "path": "internal/lithesdk/lithe/errors.go", + "sha256": "306d52fd3ec4b7acf7e67f9f575dfcb736798776c4d1d5a5144b1651921c7c99" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/framing.go", + "path": "internal/lithesdk/lithe/framing.go", + "sha256": "e2bc2938af8956cbc8948fdfccf1800276e8c2495480fcd430936be75eb8e166" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/host.go", + "path": "internal/lithesdk/lithe/host.go", + "sha256": "926f8b1b7d7f031430290f789f9f8e87dcdabdd24e324b2f8294be7d0260daa2" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/protocol.go", + "path": "internal/lithesdk/lithe/protocol.go", + "sha256": "054f7c711032abc6e3907fae3f54ecb3a208e05457a2a0ea831b7a9ee1ef4463" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/stdio_dup2.go", + "path": "internal/lithesdk/lithe/stdio_dup2.go", + "sha256": "0da3cc2be03baa00733731c6783f6a486dc8603667aea1d14ee1794efab65b0f" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/stdio_linux.go", + "path": "internal/lithesdk/lithe/stdio_linux.go", + "sha256": "bfde8bb17da9dfbd6bade1b7e419c9869f42802f420e84363849a0d4add542db" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/stdio_other.go", + "path": "internal/lithesdk/lithe/stdio_other.go", + "sha256": "8a39bdf4ab941d84718c95d723ec1fc98bfbeb2ab54aa6895e262ec9ddbb1c78" + }, + { + "upstream": "shared/plugins/sdk/go/lithe/view.go", + "path": "internal/lithesdk/lithe/view.go", + "sha256": "8a834b87a751f91cd597c7f92d9f754647a01e179ac0fe133dade23c876f7598" + } + ] +} diff --git a/vendor/LICENSE b/vendor/LICENSE new file mode 100644 index 0000000..69bef1d --- /dev/null +++ b/vendor/LICENSE @@ -0,0 +1,203 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or + Object form, that is based on (or derived from) the Work and + for which the editorial revisions, annotations, elaborations, + or other modifications represent, as a whole, an original work + of authorship. For the purposes of this License, Derivative Works + shall not include works that remain separable from, or merely link + (or bind by name) to the interfaces of, the Work and Derivative Works + thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of + its distribution, then any Derivative Works that You + distribute must include a readable copy of the attribution + notices contained within such NOTICE file, excluding those + notices that do not pertain to any part of the Derivative + Works, in at least one of the following places: within a + NOTICE text file distributed as part of the Derivative Works; + within the Source form or documentation, if provided along with + the Derivative Works; or, within a display generated by the + Derivative Works, if and wherever such third-party notices + normally appear. The contents of the NOTICE file are for + informational purposes only and do not modify the License. + You may add Your own attribution notices within Derivative + Works that You distribute, alongside or as an addendum to + the NOTICE text from the Work, provided that such additional + attribution notices cannot be construed as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing + the origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as + a result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[ ]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.