diff --git a/.agents/docs/2026-11-21-editor-surfaces-and-feature-matrix.md b/.agents/docs/2026-11-21-editor-surfaces-and-feature-matrix.md new file mode 100644 index 0000000..b8cd8e2 --- /dev/null +++ b/.agents/docs/2026-11-21-editor-surfaces-and-feature-matrix.md @@ -0,0 +1,874 @@ +# Editor surfaces and the feature matrix: one rule for every plugin, with Zed and Helix + +Status, 2026-11-21: accepted. Stream F (the fixes) is implemented in series 1.6.0; the section +"Stream F as implemented" records where the implementation differs from the plan. Streams S and E (the +surfaces, Zed and Helix) are not implemented and follow in pull requests of their own. The facts about +this repository were read from `main` (7c411fb) and from mcpp-ide 1.5.0 run over its protocol. The facts about Zed +and Helix come from their documentation and issue trackers and were not run; the section +"Unverified facts" lists them. The facts about mcppls were read from its repository at release +0.23.0. + +## Scope + +The record answers three questions raised by the issue review of 2026-11-21 (#12 and the CLion +reports of #13): + +1. How Zed and Helix are supported, given that neither lets a plugin draw a panel. +2. How each plugin states, feature by feature, whether it reuses a shared implementation, implements + the feature natively, or does not offer it. +3. How that statement is kept true by tooling and not by convention. + +It also states how mcpp-ide stands beside mcppls, what the other repositories change, the fixes +and checked versions of the CLion plugin (#13), where each request for something on screen is +placed (#13, #15 to #18), and the plan of the work with its dependencies. + +## The problem + +The backend owns every decision, and three plugins map its answers onto their editors. That holds +for decisions. It does not yet hold for presentation, where four facts were observed: + +| Observation | Where | +|---|---| +| Every `mcpp-ide/*` method needs plugin code to reach a user. An editor whose plugins cannot send a custom request reaches none of them. | Zed's extensions only name the server's command; Helix has no plugin system in a release. | +| The same view is rendered three times. The graph becomes mermaid text in `webui/src/graph.ts`, an indented list in the Neovim plugin's `graph_text`, and VS Code's own page. | `webui/`, `mide-plugins/nvim/lua/mcpp/views.lua` | +| A command's flow is repeated per plugin. A cleanup is planned, confirmed at its danger level and applied in `Dispatch.kt`, in `commands.lua` and in the extension. The sequence is a decision; only the dialog is presentation. | the three plugins | +| What an editor does not offer is recorded for commands only (`omitted` in `spec/commands.json`). For views, tests, debugging and status there is no record, and a missing surface at run time is a crash. | #13: the graph page without the JCEF plugin | + +The backend also branches on editor names (`spec::offered_in`, `vscodeArguments`), and a client that +names no editor is treated as VS Code. The project's rule for mcpp is "capabilities, not versions". +The same rule is not yet applied to editors. + +## The model + +### Surfaces + +A surface is one way a feature reaches a user. There are seven. Five are implemented once, outside +the plugins. + +| Surface | What it is | Implemented in | Plugin code | +|---|---|---|---| +| `native` | the host's own component over an `mcpp-ide/*` view model: a tree, a form, a test explorer, a debugger session | each plugin | yes | +| `webui` | a page of `webui/` in a web view the host provides | `webui/`, once | a host for the page | +| `lsp` | standard LSP: completion, hover, definition, symbols, diagnostics, code actions, code lenses, `workspace/executeCommand`, `$/progress`, `window/showMessageRequest`, `workspace/applyEdit`, `workspace/configuration` | the backend, once | none | +| `document` | a view the backend renders to a file (Markdown, Mermaid in Markdown, plain text) and opens with `window/showDocument` | the backend, once | none | +| `task` | the backend's one-shot command line in the host's terminal or task runner | the backend, once | a declaration at most | +| `host` | the editor or another extension provides it; this project provides nothing (bracket pairing by the host's TOML language, C++ features by mcppls) | -- | none | +| `omitted` | not offered, with a reason and the party that could change it | -- | none | + +### Rules + +1. **One implementation per surface.** `lsp`, `document`, `task` and `webui` are written once. A + plugin writes only `native` code and the host of a `webui` page. +2. **Native is justified, not assumed.** A plugin implements a feature natively when its host has + the API and the native component gives an interaction the shared surfaces cannot: a tree with + actions, a test explorer, a debugger, a terminal. Otherwise it reuses. +3. **Every cell is stated.** For each feature and each editor exactly one surface holds. `omitted` + carries a reason and names the party (the editor's API, an upstream issue, this project's plan). + An empty cell fails CI. +4. **Native is declared, the rest is resolved.** A `native` or `webui` cell means code in that + plugin, so the editor's row declares it, with what it falls to (`clion: ["webui", "native"]` for + a graph). For every other cell a feature lists the shared surfaces that can deliver it, best + first, an editor lists the shared surfaces its host has, and the cell is the first match. Where + nothing matches, an `omitted` reason is required. +5. **Resolution continues at run time.** The client states its surfaces at `initialize`. When a + surface is absent in a running editor (the JCEF plugin disabled, `showDocument` unsupported), the + next surface is used. When none remains, `capabilities/explain` answers the feature with + `source: "editor"`, as it answers `source: "mcpp"` today. +6. **No editor name in a decision.** `editor` identifies the client for strings, icons and reports. + Behaviour follows the stated surfaces. A client that names no editor is the profile `lsp`. Data + frozen by parity (`vscodeArguments`, the deprecated ids) may be keyed by VS Code's identity; it + is data of 0.9.0, not a decision. +7. **A flow is the backend's.** Over `lsp`, `workspace/executeCommand` runs the whole flow and asks + the client through standard requests. A command that requires acknowledgement is offered only to + a client that can ask for it. +8. **VS Code's pages stay frozen.** Parity with 0.9.0 holds for the existing pages. A new feature + reaches VS Code through `lsp` or a native component (a QuickPick), not through a changed page. + +### Editor tiers + +| Tier | Editors | The plugin is | Speaks | +|---|---|---|---| +| A, hosted plugin | VS Code, CLion, Neovim | code over the host's UI API | `mcpp-ide/*` and LSP | +| B, declarative extension | Zed | declarations: the server's command, tasks, a debug locator | LSP only | +| C, configuration | Helix; any LSP client (Emacs eglot, Sublime LSP, Kate) | a configuration snippet | LSP only | +| -- | agents and scripts (`editor: "cli"`) | none | `mcpp-ide/*` | + +Tiers B and C rest on the same backend work. Supporting both costs one backend change and two small +directories, which is why the answer to "Zed and Helix, both" is yes. + +## Two language servers, side by side + +### The present arrangement + +An editor in an mcpp project speaks to two servers, and neither passes through the other. + +| | mcppls | mcpp-ide | +|---|---|---| +| Serves | every C and C++ file | `mcpp.toml`, and the rules of `build.mcpp` | +| Reaches the editor through | its own integration (mcppls's `editors/`: VS Code, CLion, Neovim, Zed, agents) | this repository's plugins | +| Runs without the other | yes; it needs no mcpp-ide and no mcpp project | yes; without mcppls the C++ features are the editor's own | + +The backend is not on the path of a C++ request. What it knows of mcppls it reads out of band: +`mcppls --version`, `mcppls status --format json`, the payload's `payload.json`. Both read mcpp's +result record, so a build refreshes mcppls with nothing forwarded. `build.mcpp` is the one file +both answer; the plugin tells the backend whether mcppls serves it (`mcpplsServes`), and the backend +then leaves it what a compiler answers better. + +### The alternatives + +| Arrangement | Effect | Verdict | +|---|---|---| +| Peers, as now | each product stands alone; the editor merges two servers, which VS Code, Neovim, Zed and Helix all do, and CLion does through its plugin | kept | +| mcpp-ide in front of mcppls, one server to the editor | every C++ keystroke crosses the backend; the backend must pass on every LSP feature mcppls has or gains; a fault of one stops both; the two versions bind | rejected: it contradicts "mcppls: every language feature of C++ files" and mcppls's independence | +| mcppls answers `mcpp.toml` too | mcppls would take the rules of mcpp's files and a dependency on an mcpp project | rejected: mcppls serves projects of any build tool | +| One editor extension that starts both | a second copy of mcppls's integration, in step with neither repository | rejected | + +### The rule + +The two servers are peers that meet in data, never on a wire: mcpp's result record, `mcppls +status`, and what each states of itself. Three consequences follow. + +1. **Each repository owns its integrations.** An editor has an mcppls integration and an mcpp-ide + integration. Neither carries, starts or proxies the other's server. The row "C and C++ language + features" of the matrix is `host` in every column. +2. **`build.mcpp` is divided once.** The backend answers the rules a compiler cannot (the diagnostics + of SPEC-007, the directives' snippets) and leaves the rest when mcppls serves. A client of tier B + or C has no plugin to say so; there `mcpplsServes` is a setting whose default is what the backend + itself finds (`languageService/status` is `ok`). +3. **mcppls's commands stay mcppls's.** The `forward` rows of `spec/commands.json` exist for VS + Code's manifest of 0.9.0 and are not extended to another editor. Elsewhere mcppls's actions are + reached through mcppls's own integration; the backend shows its state and what to install. + +A missing mcppls is already a check of `initialize` (`languageService`). Over `lsp` it becomes one +`window/showMessage` naming mcppls's integration for that editor, since Zed and Helix have no +dependency between extensions. + +## The feature matrix + +### The source + +A new file, `spec/editors.json`, holds three lists. The backend embeds it, as it embeds the rest of +`spec/`. + +```json +{ + "surfaces": ["native", "webui", "lsp", "document", "task", "host"], + "editors": { + "zed": { "tier": "B", "has": ["lsp", "document", "task"], "documentFormats": ["mermaid", "markdown", "text"], "evidence": "compiled" }, + "helix": { "tier": "C", "has": ["lsp", "document"], "documentFormats": ["text"], "evidence": "declared" } + }, + "features": [ + { "id": "graph.packages", + "shared": ["document"], + "declared": { "vscode": ["native"], "jetbrains": ["webui", "native"] }, + "omitted": {} }, + { "id": "status", + "shared": [], + "declared": { "vscode": ["native"], "jetbrains": ["native"], "nvim": ["native"] }, + "omitted": { "zed": { "party": "editor", "reason": "Zed's extensions add no status item; a job's progress is LSP's." } } } + ] +} +``` + +`evidence` is the strength of the claim, in the three tiers of the documentation style: `e2e` (run +in CI inside the editor), `compiled` (the package builds and its declarations are checked), +`declared` (checked against the LSP conformance suite only). + +### What is generated and checked + +| Tool | Does | +|---|---| +| `mcpp-ide-dev check-editors` | resolves every cell; fails on an empty cell, an unknown surface, an `omitted` without party and reason, or a command whose feature no editor resolves | +| `mcpp-ide-dev gen docs` | writes the matrix into `docs/editors.md` and the editors table of both READMEs; CI expects no diff | +| each plugin's test | the surfaces the plugin sends at `initialize` equal its row in the spec | +| `capabilities/explain` | answers every feature for the connected client with its surface, or the reason it has none | + +`spec/commands.json` gains `feature` on each command. `editors` and `omitted` there are then derived +and removed, after one series in which both are checked to agree. + +### Initial content + +The cells below are the proposal. The columns of the three existing plugins follow +`docs/architecture.md` and their sources; implementation fills each from the code and corrects this +table where they differ. Parentheses name the component. + +| Feature | VS Code | CLion | Neovim | Zed | Helix | +|---|---|---|---|---|---| +| `mcpp.toml` completion, hover, jumps, diagnostics | `lsp` | `native` (the platform's LSP client would start a second server) | `lsp` | `lsp` | `lsp` | +| `build.mcpp` rules | `lsp` | `native` | `lsp` | `omitted` at first: see the review | `omitted` at first | +| Pairs and comments in `mcpp.toml` | `native` (language configuration, to add) | `host` | `host` | `host` | `host` | +| The command table | `native` (palette, menus) | `native` (actions) | `native` (`:Mcpp`) | `lsp` (code actions, code lenses) | `lsp` (code actions, `:lsp-workspace-command`) | +| Build, test and cleanup jobs | `native` (pseudoterminal, Problems) | `native` (console) | `native` (buffer) | `lsp` (progress, diagnostics) | `lsp` | +| Running the program | `native` (terminal) | `native` (run configuration) | `native` (terminal) | `task` | `omitted`: no terminal; the command line runs it outside | +| Debugging | `native` | `native` | `native` (nvim-dap) | `native` (debug locator), after verification | `omitted`: static DAP templates | +| Test tree | `native` (Testing) | `native` | `native` | `omitted`: no test API; results are diagnostics | `omitted`: same | +| Test insights | `native` (page) | `webui` | `document` | `document` | `document` | +| Project view | `native` (tree) | `native` (tree) | `document` | `document` | `document` | +| Targets, toolchains | `native` | `native` | `native` (`vim.ui.select`) | `lsp` (message request) | `lsp`, or settings | +| Libraries | `native` (page) | `native` | `native` | `lsp` (dependency completion) | `lsp` | +| Cache inventory | `native` (page) | `native` (tree) | `document` | `document` | `document` | +| Dependency and module graphs | `native` (page) | `webui`, then `native` (a tree) | `document` (text) | `document` (Mermaid) | `document` (text) | +| Pack | `native` | `native` | `native` | `omitted` in the first release | `omitted` | +| Settings | `native` | `native` (generated form) | `native` (`setup()`) | `lsp` (`workspace/configuration`) | `lsp` (`config`) | +| Status item | `native` | `native` | `native` (statusline) | `omitted`: no API | `omitted`: no API | +| Self-check, report | `native` | `native` | `native` | `document` | `document` | +| mcppls's own commands | `native` (forward) | `omitted` | `omitted` | `omitted` | `omitted` | +| C and C++ language features | `host` (mcppls) | `host` (mcppls) | `host` (mcppls) | `host` (mcppls) | `host` (mcppls, once it has a fragment) | + +Two cells change an existing plugin. CLion's graph falls to a native tree when JCEF is absent, which +is rule 5 applied to #13. Neovim's views become the backend's text, which removes `graph_text`, +`cache_text` and `targets_text` from the plugin. + +## The backend's part + +### The `lsp` profile + +- `initialize` reads the client's LSP capabilities: `window.showDocument`, `window.workDoneProgress`, + `window.showMessage.messageActionItem`, `workspace.applyEdit`, `workspace.configuration`, + `textDocument.codeAction`, `textDocument.codeLens`. They become the session's surfaces. A plugin of + tier A adds its own in `initializationOptions.surfaces`. +- The server states `executeCommandProvider` (the command table's ids resolved for the client), + `codeActionProvider` and `codeLensProvider` only to a client whose commands resolve to `lsp`. A + plugin of tier A is answered as today: VS Code's and Neovim's language clients show whatever a + server advertises, and would otherwise gain a second set of commands beside their own. +- The additions are standard LSP methods and new fields. The protocol stays 2, and + `protocol/protocol.schema.json` and the method list gain them together. +- A code action is the canonical way to a command, since every LSP client has it. A code lens is an + addition: Zed has it behind a setting, Helix does not. On `mcpp.toml`, `[package]` offers build, + test and clean; `[targets.]` offers build and run of that target; `[dependencies]` offers the + graphs. +- `workspace/executeCommand` runs a command as the plugins' dispatchers do today. A job reports + through `$/progress`, its narration through `window/logMessage`, its diagnostics through + `textDocument/publishDiagnostics` on the files they name. A confirmation is a + `window/showMessageRequest` whose actions are the plan's. +- Settings arrive through `workspace/configuration` (section `mcpp`) and + `workspace/didChangeConfiguration`, and pass the validation that exists. +- The language is LSP's `locale`. Titles of actions are the backend's strings, as now. + +### The `document` surface + +- `views.cppm` gains renderers beside the view models: `text`, `markdown` and `mermaid`. The + flowchart that `webui/src/graph.ts` builds moves here, so the page, Neovim, Zed and an agent read + one text. `graph/packages` and `graph/modules` accept `format`. +- A document is a file in the backend's own state directory, keyed by project, never in `target/`, + which is mcpp's. It is rewritten when its view changes (`result/changed`, `manifest/changed`). +- A module's node links to its source by path, so the host's own link handling opens it. +- A document is a view. Its actions stay on `mcpp.toml`, where code actions exist. + +### The `task` surface + +`mcpp-ide job [--root] [--target] [--profile]` runs one job on the session's code path and +writes the narration to standard output. `mcpp-ide view --format ` prints a document. +`mcpp-ide launch --format json` prints the launch a debugger needs. + +### A command line beside a session + +A task is a process of its own. Beside an editor's session it differs from that session in four +ways, of which the settings are only the visible one. + +| What the session holds | A separate process | +|---|---| +| the settings a job runs with (`mcpp.path`, `mcpp.build.profile`, `mcpp.build.target`, `mcpp.task.*Args`, `mcpp.trust.denyEffects`, `mcpp.runtime.*`) | takes flags, so two builds of one project can differ | +| the project's lane: one job at a time, a newer one replacing a waiting one | runs beside the lane | +| the job's diagnostics, published to the editor | prints them; Zed's tasks have no problem matcher, so they never reach the editor | +| cancellation and the views that follow a job | none; the views follow only through mcpp's result record | + +Four arrangements were weighed for the long term. + +| Arrangement | Verdict | +|---|---| +| Flags only | the first release. It is the divergence itself. | +| A settings file of the backend's in the project | refused. Tier A's editors have settings of their own, so the file is a second source with a precedence to define, and it mends the first row only. | +| The settings in mcpp's own configuration | right for what is the project's and mcpp already reads (`[build] default-profile`): every route, a terminal included, then agrees with no work here. Not for a user's current choice of target, which is not the project's to commit; and mcpp is not changed. | +| The command line attaches to the project's running session | the long-term arrangement. | + +**Attaching.** A session is the one holder of a project's job state, and a command line is one more +client of it. `mcpp-ide job` looks for a running session of the project. When it finds one it asks +that session to run the job and prints the narration the session streams back. When it finds none +it runs alone, with flags and the defaults, as `editor: "cli"` does today. All four rows above then +hold: the settings and the selected target are the session's, the job waits in the project's lane, +its diagnostics appear in the editor, and it can be cancelled from either side. + +The same arrangement serves an agent working beside an editor (its build is seen in the editor and +does not run over the user's) and a terminal inside Neovim. It is therefore not a feature of Zed. + +What it needs, and why it is not in the first release: + +- An endpoint. The session listens on the loopback interface (`mcpplibs.os` 0.4.2 has a loopback + listener) and writes a record in the backend's state directory: the project's root, the process, + the port, a token, the series. The file is the user's alone and the token is required. A record + whose process has ended is ignored and removed. +- The series rule. A command line of another series is refused, as a plugin is. +- Several sessions of one project (two editors open). The newest is taken unless one is named. +- Trust. An attached job runs with the session's trust and its denied effects. +- More than one connection per session. Today a session has one connection, and every notification + goes to it. A job's events must go to the connection that started the job and to the editor's. + This is the cost, and it is the backend's to design in a record of its own. + +Until then the first release keeps the divergence small: the generated tasks pass no option, so a +task and a code action differ only when a user has set a job setting, and the README of each tier B +and C editor says that job settings apply to commands started in the editor. + +## The two new adapters + +### Helix, tier C + +`mide-plugins/helix/` holds a `languages.toml` fragment and a README. Nothing else exists to write: +by the upstream pull request (helix#8675, labelled experimental in October 2026) no release has a +plugin system. + +```toml +[language-server.mcpp-ide] +command = "mcpp-ide" +args = ["serve"] +required-root-patterns = ["mcpp.toml"] +config = { editor = "helix" } + +[[language]] +name = "toml" +language-servers = ["taplo", "mcpp-ide"] +``` + +The backend is attached to the host's TOML language and answers only `mcpp.toml`; other documents +are of kind `other` and get nothing, as today. No grammar and no query files are shipped, and +pairing and comments are the host's. Commands are code actions and `:lsp-workspace-command`. A +graph is the text document. Running and debugging are `omitted`. + +The C++ entry is not this fragment's. Which files are C++ (`build.mcpp`, `.cppm`) and which server +answers them first is mcppls's to state, in a fragment of its own (section "Work across +repositories"). The backend is not attached to C++ in the first release (section "Review of this +record", finding 2). + +### Zed, tier B + +`mide-plugins/zed/` is an extension: `extension.toml`, a Rust crate compiled to WebAssembly, tasks +generated by `mcpp-ide-dev gen zed`, a debug locator. It follows mcppls's Zed extension +(`editors/zed` there, released as 0.23.0), which is the same kind of thing and already passes a run +in a real Zed in that repository's CI. + +- The crate answers the server's command: `mcpp-ide` on `PATH` (xlings), else the backend of the + extension's own series, downloaded from the release. It declines when the worktree has no + `mcpp.toml`, so the backend starts only in an mcpp project. +- The server is declared for the host's TOML language. C++ follows later (section "Review of this + record", finding 2); an extension cannot add a suffix to a language Zed defines (mcppls's README), + so `build.mcpp` is C++ only with the user's `"file_types": { "C++": ["mcpp"] }`. +- Tasks are the first way to build, run and test in Zed: they are in the task picker from any file. + Code actions exist only in `mcpp.toml`, and code lenses are off by default. +- Tasks call `mcpp-ide job`. A task that called `mcpp build` directly would skip the profile, the + target and the denied effects, which are the backend's decisions. +- A graph is Mermaid in Markdown, which Zed's preview renders (stable 0.225.9 and later). +- The debug locator turns the run task into a scenario of Zed's own adapters from + `mcpp-ide launch`. +- A context server for Zed's agent is a later addition over the same backend as `agents/`. + +### Versions and release + +Zed's `extension.toml` becomes a seventh statement of the version, with the tag `zed-vX.Y.Z`. The +Helix fragment states no version; it starts the `mcpp-ide` on `PATH` and is released with the +series. `components.tsv` gains `zed` and `helix`. `spec/editors.json` is a backend path, so its +introduction begins a series. + +## Work across repositories + +### The parties + +| Repository | Owns here | Changes for this design | +|---|---|---| +| mcpp | the machine contract | none for Zed and Helix; one request, a package's features | +| mcppls (`Sunrisepeak/mcpp-language-server`) | C and C++ in every editor; its `editors/` | a Helix fragment, `editors/helix`; nothing else | +| mcpp-ide | the project layer; `mide-plugins/` | everything in this record | +| the xlings index | the packages `mcpp-ide`, `mcpp-ide-nvim` | none: Helix and Zed start the `mcpp-ide` package | +| `zed-industries/extensions` | Zed's registry | one entry, pointing at `mide-plugins/zed` | + +### mcppls and Helix + +mcppls is a standard LSP server, so Helix needs from it what it needs from mcpp-ide: a fragment and +a README, as mcppls already ships configuration fragments for other clients. It belongs in mcppls's +repository by the rule above. It is worth doing for its own sake: without it a Helix user's C++ is +clangd with no module database, whatever mcpp-ide does. + +### The points where the two repositories must agree + +No code is shared and no release waits for the other. Four statements must be the same in both. + +| Statement | Owner | The other repository | +|---|---|---| +| The servers' names in an editor's configuration: `mcppls`, `mcpp-ide` | each its own | uses the name as given | +| The C and C++ language entry of an editor: its file types (`build.mcpp`, `.cppm`), the order of its servers, clangd off | mcppls | adds one server to the list; never restates the entry | +| The TOML language entry | mcpp-ide | -- | +| The division of `build.mcpp` | mcpp-ide's `docs/rules.md` | mcppls links to it | + +Helix makes the second row necessary: a language's `language-servers` is one list, and two +fragments that each set it overwrite one another. Each README therefore shows its own +`[language-server.]` table, which merges, and the same combined `[[language]]` line with the +other server marked optional. + +### The order + +1. mcpp-ide phases 0 and 1 need nothing from mcppls. +2. mcppls's Helix fragment and mcpp-ide's (phase 2) are independent. Each README links the other + when the other exists. +3. mcpp-ide's Zed extension (phase 3) is written beside mcppls's and reuses its approach to + installing and to testing in a real Zed. +4. One tracking issue in mcpp-ide lists the linked issues of the other repositories. A pin names + only a released version, as AGENTS.md states. + +## CLion: the fixes of #13 and the versions it is checked on + +### The fixes + +Four defects of mcpp-clion 1.5.0 were confirmed in the source. Each is the plugin's and is fixed +there. They are part of the one pull request of fixes (section "The fixes as one pull request per +repository") and do not wait for the surfaces. + +| Defect | Cause | Fix | Rule it becomes | +|---|---|---|---| +| "Read access is allowed from inside read-action only", at startup and on the backend's start | `McppDocuments.reopen()` reads documents from the startup coroutine and from the thread that reads the backend's output | the reading thread decodes frames and completes futures; listeners run on an executor; `reopen()` takes its snapshot in a read action | the reading thread runs no listener | +| `NoClassDefFoundError: JBCefApp` on opening a graph | the dependency on `com.intellij.modules.jcef` is optional, and `JcefPage`, a class of the core, links to JCEF's classes. The existing guard, `JBCefApp.isSupported()`, is the call that fails. | a page-host interface in the core; its JCEF implementation registered only in `mcpp-jcef.xml`; no JCEF import outside that package | rule 5: an absent surface resolves to the next | +| A tooltip in English beside Chinese rows | the toolbar's texts are read once at construction, before `i18n/bundle` arrives; the translations exist | texts are set when presented (`update()`), tab titles again when the session starts | a string is read when shown | +| Seven identical buttons on the cache tab | the tab lacks the two sections VS Code's page has, and draws every command as one icon in a toolbar | the sections Project and Shared cache, each with its actions (section "The interface") | an action sits on what it acts on | + +The issue's own proposals for the second and third are not taken: the dependency is already +declared and the guard already present, and an IntelliJ resource bundle would move strings out of +the backend. + +### The versions + +| | Now | Gap shown by #13 | +|---|---|---| +| Installs on | build 261 and later, no upper bound | -- | +| Built against | 2026.2.3 (`platformVersion`) | -- | +| Verified statically | 2026.1 and 2026.2.3 | -- | +| Run in a real IDE | 2026.1.5.2 and 2026.2.4.1, on Linux x86_64 only | the report is from macOS aarch64; JCEF is a bundled plugin built per system and architecture | +| Without JCEF | `ide.browser.jcef.enabled=false`: JCEF present and switched off | the JCEF plugin absent or disabled was never run | +| Errors the IDE logs | not a failure | both threading errors are logged, not thrown, so the runs passed | +| mcppls plugin | 0.21.0 (`mcpplsPluginVersion`) | mcppls is at 0.23.0 | + +The proposal: + +1. **The real-IDE run fails on any error the IDE logs from this plugin.** This one gate would have + caught both threading paths, and catches the next of their kind. +2. **A run with the JCEF plugin disabled** (`disabled_plugins.txt`) beside the run with JCEF switched + off. +3. **A run on macOS aarch64** of the newest stable CLion, at least for the startup chain and the + graph. Whether a stock 2026.2.4 on macOS gives a plugin JCEF is not known; this run answers it, + and the answer decides whether the defect reaches every macOS user or one installation. +4. **Three versions are named and moved together**: the oldest claimed (2026.1), the one built + against, and the newest stable, which the real-IDE run uses. A scheduled job runs the verifier + and the real-IDE run on the newest stable release, so a new CLion is met by CI before by a user. +5. **`mcpplsPluginVersion` follows mcppls's releases**, as a pin of a released version. + +## The interface + +### The principles + +A change on screen is placed by five statements. They hold for the changes below and for later ones. + +1. **One information structure, each host's components.** A view model is a list of sections; a + section has a title, its measures, its rows and its actions. VS Code's page draws a section as a + block, CLion as a top-level node of a tree, Neovim and the `document` surface as a heading. What + is shared is the structure and its order, not a widget. +2. **VS Code's pages are the reference structure.** They exist, are frozen by parity and were + designed as pages. A view in another editor that orders the same facts differently is the one + that changes. +3. **An action sits on what it acts on.** An action of a section is drawn with that section. A + toolbar holds only what acts on the whole view (refresh). +4. **No colour of this project's own.** Text, icons and emphasis are the host's: the theme's + variables in VS Code, `SimpleTextAttributes` and `AllIcons` in CLion, highlight groups in Neovim, + the host's theme in a Mermaid document. Kinds of things differ by shape, stroke, icon or a word + (`webui/graph.ts` already marks an external node by a dashed stroke and a test by a thick one), + so a view reads the same in a light theme, a dark theme and plain text. +5. **Danger is a confirmation, not a colour.** The plan's level decides the confirmation: none, + a modal with the preview, a second acknowledgement. A button is not painted red in any editor; + VS Code's page does not, and a coloured border is no IntelliJ component. + +What is reused, by kind: + +| Reused | Where it lives | Used by | +|---|---|---| +| the structure (sections, their order, their actions) | the backend's view model | every editor | +| the text of a view (`text`, `markdown`, `mermaid`) | the backend's renderers | Neovim, Zed, Helix, agents | +| a page | `webui/` | CLion's JCEF host; a browser | +| a tree of sections | one component per plugin (`Row`, `RowNode`, `RowRenderer` in CLion) | every tab of that plugin | +| the strings | `spec/i18n` | every editor | + +### The cache view (#13) + +VS Code's page has two blocks, and its six actions sit in them under their titles: + +| Block | Measures | Actions | +|---|---|---| +| Project (`target/`) | its size | Clean stale, Clean project | +| Shared cache | size and entries; composition by kind; by last use; the largest | Verify, Collect to a budget, Prune, Remove the legacy cache (when one exists) | + +CLion's tab has the shared cache's rows only, flat, and every action as one icon in a toolbar. The +report (seven identical buttons, no grouping) is the absence of this structure. The tab takes it: + +```text +[Refresh] +v Project target/ Clean stale... Clean project... +v Shared cache 3.4 GiB in 212 entries Verify Collect... Prune... + v By kind + pkg 2.1 GiB · 150 entries + std 1.3 GiB · 2 entries + > Largest + > By last use + ! 3 incomplete entries +> Legacy cache Remove... +``` + +- **Placement.** The toolbar keeps Refresh. A section's actions are that node's: links at the right + of its row, and the same entries in its context menu and on the keyboard. An ellipsis marks an + action that asks before it acts. +- **What the backend adds.** `commands/list` gives a cache command its `scope` (`project` or + `shared`, the plan's `group`) and its `level`. The plugin places a command by its scope and + invents no grouping. Two commands with one plan (`mcpp.clean`, `mcpp.cleanProjectArtifacts`) are + one action in the view. +- **The palette.** The commands stay in the palette and the menus as they are; the view's actions + are the same commands (decided 2026-11-21: both stand). +- **Colour.** None. The warning icon stays on the incomplete entries, where it reports a state. +- **Other editors.** Neovim's cache text and the cache document take the same two headings; over + `lsp` the actions are code actions. + +Three requests of the report are answered by this and need nothing more: grouping, in-place +actions, and labels. Its remaining requests: + +| Request | Disposition | +|---|---| +| Clean one kind from its row (`pkg`, `std`) | taken as a feature of every editor, after the fixes (decided 2026-11-21; task S7 of the plan). The plans exist (`cacheDeps`, `cacheStd`) and no editor offers them. Two commands join the command table; the rows `pkg` and `std` carry them in CLion, in Neovim's text and in the cache document. In VS Code they are in the palette and in the context menu of the sidebar's cache tree, which parity admits (it forbids changing or dropping what 0.9.0 contributed, not adding); the page is unchanged. | +| Highlight what a button affects | not taken: an action on its own section needs none | +| Confirm with the size to be freed | present: `cache/plan` gives the level and the preview | +| Red for dangerous actions | not taken: principle 5 | + +### Strings (#13) + +A tooltip in English is a text read before the bundle arrived, fixed in the plugin. An IntelliJ +resource bundle and a lint for hard-coded strings are not taken: the strings are the backend's, and +`check-i18n` already holds English and Chinese together. + +### A dependency's features (#16, #17) + +mcpp is not changed from here. A request is made of mcpp (an issue there, decided 2026-11-21), and +what it would enable is not built until mcpp states it. mcpp states no features of an index package: +`mcpp search --format json` and `mcpp xpkg parse --format json` were run on a package that declares +one (`compat.harfbuzz`, `no-freetype`) and neither answer names it. Reading the index's descriptors +from disk is excluded by "Only mcpp's contract". What can be answered is what the text of a +manifest shows, which is the rules layer's own ground: + +| Dependency | Its features are read from | Offered | +|---|---|---| +| given by `path`, or a workspace member | that manifest's `[features]`, which the rules layer already opens for the jump from `path = "../x"` | completion in `features = [...]`, hover, the diagnostic `mcpp.manifest.unknownFeature`, code actions "Enable feature" and "Disable feature" | +| the project's own `[features]` | the open document | as today (the jump to `[features.]`) | +| from an index | nothing mcpp states | nothing yet; `capabilities/explain` says that mcpp states no features of an index package and names the issue that asks for it, as it names mcpp#917 for the tests | + +- **Placement.** In `mcpp.toml`, on the dependency, where the array is written. No panel, no page + and no sidebar entry changes. It is on `lsp`, so the five editors have it alike with no plugin code. +- **Layout.** A hover lists each feature on a line: its name, "default" as a word when it is one, + and the names it implies. A manifest has no description of a feature, so none is shown. +- **The checkboxes the issues ask for** are kept as a design and not built: a section "Features" in + a package's detail, under its description, one checkbox with name and description per feature, + "default" as a word. They need an index package's features and wait until mcpp states them. + +The larger part of what #16 and #17 ask, index packages, is answered when mcpp states them. The +request asks for each feature's name, whether it is a default, what it implies and a description, +by package and version, in a JSON query, with a name in `features` for the capability. The user +documentation notes the limit: features are completed for `path` and workspace dependencies. + +### Editing `mcpp.toml` (#15, #18) + +| Request | Disposition | +|---|---| +| Quotes and brackets close | VS Code's language configuration for `mcpp-toml`, which also gives `#` comments and bracket matching; `host` elsewhere | +| Keys inside `{ }` | one rule of the rules layer: an inline table at a key is read as the table of that name | +| Values of `kind` | present in 1.5.0 | +| Completion that takes seconds | not reproduced: 1.3 ms in the backend. The report's version and log are needed. | +| Ctrl+X | not this project's: the extension binds no such key | + +### Graphs (#12, #13) + +A graph in CLion without JCEF, in Zed and in Helix is one request, a graph where no web view +exists, with one answer by principle 1. The view model is one section per package with the packages +it depends on as rows. CLion draws it as a tree in the graph's own tab, with the tab's other +component and no new place; Zed reads it as Mermaid; Helix and Neovim as text. + +## The fixes as one pull request per repository + +The fixes are made together and land as one pull request in each repository. AGENTS.md asks that a +pull request do one thing; here the one thing is the fixes of the review of 2026-11-21, and each +fix is a commit of its own so that the squash message lists them. + +| Repository | The pull request | Contains | +|---|---|---| +| mcpp-ide | `fix/issue-review-2026-11-21`, series 1.6.0 | CLion: the four fixes, the cache tab's sections, the added runs. VS Code: the language configuration and the parity gate. Backend: inline tables in the rules layer, features of `path` and workspace dependencies, `scope` and `level` on cache commands. CHANGELOG and the affected docs. | +| mcppls | one, in its repository | the Helix fragment | +| mcpp | an issue | a package's features in a JSON query. Nothing here waits for it. | + +The surfaces (phases 0 to 4) are not fixes and follow in pull requests of their own. + +A draft pull request is the place for what cannot be run on a developer's machine. Three uses are +foreseen, each closed or converted when it has answered: + +1. The added CLion runs first, without the fixes, to see them fail on the defects: the logged-error + gate, the JCEF plugin disabled, macOS aarch64. The last answers the open fact about JCEF on macOS. +2. The fixes on top, until the same runs pass. +3. The verifications of Zed and Helix, with a scripted client and a real Zed in CI. + +Opening one is an outward action and is asked for each time, as AGENTS.md states. + +## Tests + +| Layer | Test | +|---|---| +| The `lsp` surface | `tests/cts/lsp`: a scripted client in two profiles, minimal (Helix's capabilities) and full (Zed's), with golden answers for code actions, a command's flow, progress, a confirmation and a refused command | +| The `document` surface | goldens of each view in each format over `protocol/fixtures` | +| The matrix | `check-editors`; each plugin's surfaces against its row | +| Zed | the crate builds to WebAssembly in CI; the generated tasks show no diff; evidence `compiled`, then `e2e` with a run in a real Zed as mcppls's CI has | +| Helix | the fragment parses; evidence `declared` until an end-to-end run exists | +| CLion | the runs of the section on CLion: no logged error, the JCEF plugin disabled, macOS aarch64 | + +## Phases + +| Phase | Content | Reaches | +|---|---|---| +| F | The fixes, one pull request in this repository, series 1.6.0. Independent of the phases below. | #13, #15, #18 | +| 0 | `spec/editors.json`, `check-editors`, the generated table, for the three plugins and `cli` as they are. No behaviour changes. | the record exists and is checked | +| 1 | The `lsp` profile, the `document` surface with the graphs first, `mcpp-ide job` and `view` | every LSP client; agents | +| 2 | Helix: the fragment and its README | the cheapest proof of phase 1 | +| 3 | Zed: the extension, the tasks, then the locator | the Zed extension registry | +| 4 | Convergence of tier A where it removes code: Neovim's texts, CLion's graph fallback, the page's flowchart, the dispatchers' flows | less plugin code | +| 5 | A command line that attaches to the running session, after a record of its own | tasks, agents and terminals share the session's settings, lane and diagnostics | + +Phase F is a series of its own, since it changes the backend. Phases 0 and 1 are the next series. +Phase 2 precedes phase 3 because it validates the backend work with no packaging. Zed's +verification can run beside phase 0. The section "The plan of the work" divides the phases into +tasks. + +## Where the reviewed issues meet this design + +| Issue | Meeting point | +|---|---| +| #13, the CLion plugin | the section on CLion: four fixes, and the runs that would have caught them | +| #13, `std.pcm` overwritten | not this project's: mcpp writes the compilation database. No workaround, and no report from here (decided 2026-11-21). | +| #15 and #18, pairs in `mcpp.toml` | the matrix row "Pairs and comments": `native` in VS Code only. Decided 2026-11-21: the parity gate keeps every field of 0.9.0's `languages` and admits additions. | +| #16 and #17, dependency features | on `lsp`, for `path` and workspace dependencies, in five editors without plugin code. Index packages are not answered: mcpp states no features of theirs and is not changed. | +| #12, Zed | section "Zed, tier B". | + +## Unverified facts + +Unverified, to settle before the phase that needs each and recorded when settled: + +1. Zed's `window/showDocument` for a local file. It reached stable 1.21.0; an earlier report + (zed discussion #53123) says only external URLs opened. The fallback is a task that opens the file. +2. Zed's code lenses and code actions reaching `workspace/executeCommand`; code lenses are off by default. +3. A debug locator of an extension used with Zed's own CodeLLDB and GDB adapters. +4. A server declared for Zed's TOML language beside the servers already there, and the crate + declining to start outside an mcpp project. For C++ mcppls's extension shows that it works. +5. Helix's `window/showDocument` and `window/showMessageRequest`. Without the second, commands that + require acknowledgement are `omitted` there by rule 7. +6. Helix's `:lsp-workspace-command` with two servers on one language (helix#9017 reports that one + server's commands are listed). +7. Workspace trust in Zed. Helix has none and is trusted unless `config` says otherwise, as Neovim. +8. A stock CLion 2026.2.4 on macOS aarch64 giving a plugin JCEF's classes. + +## Decisions of the review, 2026-11-21 + +| Question | Decision | +|---|---| +| Where the matrix lives | a new `spec/editors.json` | +| The languages in Zed and Helix | the backend is attached to the host's languages, with no language of this project's own; TOML at first, C++ later (finding 2 of the review below) | +| The settings a task sees | flags only; no settings file of the backend's | +| Tier A's flows on `workspace/executeCommand` | done as the last item of phase 4 (C2), after tiers B and C run on the same flows | +| Helix or Zed first | Helix, then Zed | +| The parity gate on `languages` | every field of 0.9.0 kept, additions admitted | +| The compilation database of #13 | no report to mcpp from this project | +| The shape of the fixes | one pull request per repository; draft pull requests for verification | +| mcpp | not changed from here; one issue asks for a package's features. Until it states them, features are answered for `path` and workspace dependencies, and the docs note the limit. | +| `build.mcpp` in Zed and Helix | not in the first release; mcppls serves it as C++ | +| A task beside a session | flags only at first, tasks passing no option; attaching to the session in the long term (phase 5) | +| The loopback endpoint of phase 5 | read as: opened only for a client that states the `task` surface, which any plugin may state | +| Per-kind cleanups of the shared cache | wanted, in every editor, after the fixes | +| The fixes' release | together, as series 1.6.0; no patch of the CLion plugin ahead of it | +| Zed's graph and debugging | by Zed's own conventions, as Z0 finds them | +| C2 | done, last | +| The profile `lsp` | documented for other LSP clients | +| The cache view's actions and the palette's commands | both stand | +| mcppls and Helix | mcppls takes a fragment of its own | +| CLion on macOS | read as: the startup chain and the graph on every change that reaches the plugin, the whole suite in the scheduled job | + +## Review of this record + +The record was reviewed twice, from the sides named in the first column. Each finding says what was +changed in the record, or what remains a risk. + +### First review + +| Side | Finding | Outcome | +|---|---|---| +| Cost at run time | 1. Attaching the backend to the host's C++ language in Zed and Helix, for `build.mcpp` alone, sends every C++ document whole on every change: the backend's synchronisation is full, and an LSP server cannot name a file in its static capabilities. | TOML only at first; `build.mcpp` is `omitted` in tiers B and C and mcppls serves it as C++. C++ follows when the backend registers `build.mcpp` dynamically or synchronises incrementally. Confirmed 2026-11-21. | +| Consistency between editors | 2. Cleanups on the rows of a kind were taken for CLion alone in one draft, and refused for a wrong reason before that. | The sections of VS Code's page for the fix; per-kind cleanups as a feature of every editor (S7). | +| Consistency inside one editor | 3. In Zed a build from a task and a build from a code action can differ. | "A command line beside a session": four differences, mended together by attaching. Phase 5. | +| The user who reported | 4. Index packages, the main request of #16 and #17, have no answer until mcpp states a package's features. | An issue asks mcpp; `capabilities/explain` names it; the docs note the limit. | +| Release | 5. One pull request of series 1.6.0 puts two crashes of the CLion plugin behind backend work. | The commits are ordered, the CLion fixes first and verified on a draft. A part of the backend work that is not ready leaves the pull request. | +| Tests | 6. A gate on every error the IDE logs can fail on the platform's own errors. | It counts the errors the IDE attributes to this plugin's id, and the plugin's own frames. | +| Evidence | 7. The matrix's cells for the three existing plugins follow the documentation. Helix is `declared`, the weakest tier. | S0 verifies each cell. The Helix README says what was run. | +| Discoverability | 8. In Zed, a user in a C++ file has no code action of this project. | Tasks are the first way. | +| Files | 9. The `document` surface writes files that outlive their view. | The backend's state directory, per project, removed when the session ends. | + +### Second review + +| Side | Finding | Outcome | +|---|---|---| +| The model | 10. Rule 4 resolved every cell as the first surface of a feature's list that the editor has. CLion prefers the page to its own tree for a graph, and VS Code its own page to both, so one order per feature cannot be right; and `native` is not a property of a host but of code that exists. | Rule 4 rewritten: `native` and `webui` are declared by the editor's row with their fallback; only the shared surfaces are resolved. The example and the graph's cell follow. | +| Compatibility | 11. Advertising code actions, code lenses and commands in `initialize` reaches the three existing plugins too. VS Code's and Neovim's clients show what a server advertises, so each would show its commands twice. | The server advertises them only to a client whose commands resolve to `lsp`. A regression test holds the existing plugins' `initialize` answer unchanged. | +| Ownership | 12. Rule 6 forbade an editor's name outright, while parity data is keyed by VS Code. | The exception is in the rule. | +| Scope | 13. The scope still called the manifest features separate changes after they had entered the pull request of fixes. | The scope is corrected. | +| Safety | 14. A Mermaid or Markdown document carries names from manifests. The label escaping lives in `webui/src/graph.ts` today. | It moves with the flowchart into the backend's renderer, with a golden of hostile names (S3). | +| Size | 15. The pull request of fixes holds nine commits across the backend, two plugins and CI. It is one review. | Kept, as decided. The commit order makes it reviewable in three parts: CLion, the backend's three additions, VS Code. | +| Dependence on others | 16. Three things are outside this repository's control: Zed's `showDocument` for local files, Helix's support of two requests, and mcpp's answer on features. | Each has a fallback that needs none of them: a task that opens the file; commands that need acknowledgement `omitted` in Helix; features for local dependencies only. No task of the plan is blocked by another repository. | +| Maintenance | 17. Two adapters are added, and Zed's is released to a registry by a pull request to another repository at every version. | Helix has nothing to release. Zed's registry update is a step of the release procedure (the development skill), and an outward action. | +| What is left out | 18. Not designed here: the session with several connections (phase 5), `build.mcpp` in tiers B and C, a context server for Zed's agent, the checkboxes for features. | Each is named where it would start, and none is needed by an earlier task. | + +The risks that remain after both reviews are finding 16 and the size of S2, the largest task, which +moves the flows of commands into the backend for the first time. + +## The plan of the work + +### The streams + +Four streams run with few ties between them. A task names its verification; a task that touches +`spec/` or `src/` also passes `mcpp build && mcpp test`, `check-sources`, `check-i18n` and the +generators with no diff. + +**Stream X: outward actions.** Each is asked for before it is done. + +| Task | Content | Needs | +|---|---|---| +| X1 | The issue for mcpp: a package's features in a JSON query. Drafted in `.agents/reviews/`. | approval | +| X2 | The issue and pull request for mcppls: a Helix fragment, `editors/helix` | approval | +| X3 | One tracking issue in mcpp-ide linking #12, #13, #15 to #18, X1, X2 | approval | +| X4 | The entry in `zed-industries/extensions` | Z1 released | + +**Stream F: the fixes.** One pull request, `fix/issue-review-2026-11-21`, series 1.6.0. The tasks +are its commits, in this order. + +| Task | Content | Verified by | Needs | +|---|---|---|---| +| F0 | The gates alone, as the first commits of the pull request while it is a draft: errors the IDE logs from this plugin fail the run; a run with the JCEF plugin disabled; a run on macOS aarch64 | they fail on 1.5.0's defects; unverified fact 8 is answered | approval to open the draft | +| F1 | CLion threading: the reading thread runs no listener; `reopen()` in a read action | F0's gate passes; a platform test of `install()` from a background thread | F0 | +| F2 | CLion JCEF: the page-host interface, its implementation in `mcpp-jcef.xml`, no JCEF import in the core | F0's disabled-plugin run shows the explanation; a check on imports | F0 | +| F3 | CLion strings read when shown | a test that builds a view before the bundle arrives | -- | +| F4 | Backend: `scope` and `level` on the cache commands of `commands/list` | the protocol schema; a contract test | -- | +| F5 | CLion cache tab: the sections Project and Shared cache with their actions | the view's model test; the real-IDE run | F3, F4 | +| F6 | Backend: an inline table read as the table of its name | new goldens, kept apart from 0.9's; `docs/rules.md` | -- | +| F7 | Backend: features of `path` and workspace dependencies: completion, hover, `mcpp.manifest.unknownFeature`; `capabilities/explain` names X1 | goldens over a corpus with a path dependency | F6; X1 for the issue's number | +| F8 | VS Code: the language configuration of `mcpp-toml`; `gen vscode` writes it; the parity gate keeps 0.9.0's fields and admits additions | `npm test`; a test of the configuration's pairs | -- | +| F9 | The six version statements at 1.6.0; `mcpplsPluginVersion`; the scheduled CLion job; CHANGELOG; the READMEs' versions | `release-plan.sh`; CI | F1 to F8 | + +**Stream S: the surfaces.** The series after 1.6.0. Each task is a pull request. + +| Task | Content | Verified by | Needs | +|---|---|---|---| +| S0 | `spec/editors.json`, `check-editors`, `gen docs`, `feature` on each command, each plugin's surfaces tested against its row; every cell of the three plugins verified from the code | `check-editors`; no diff in the generated table | F merged | +| S1 | The session's surfaces: the client's LSP capabilities, the profile `lsp` for a client that names no editor, `capabilities/explain` with `source: "editor"`, the unchanged answer to the existing plugins | a regression test of the three plugins' `initialize` | S0 | +| S2 | Commands over `lsp`: `workspace/executeCommand` running the flows, code actions and code lenses on `mcpp.toml`, `$/progress`, `window/logMessage`, diagnostics of a job, `window/showMessageRequest`, `workspace/configuration` | `tests/cts/lsp` in two profiles | S1 | +| S3 | The sections view model and the `document` surface: renderers `text`, `markdown`, `mermaid`; the graphs first, then the cache, the project, the self-check; the state directory; `window/showDocument` | goldens of each view and format, hostile names included | S1 | +| S4 | The command line: `mcpp-ide job`, `view`, `launch` | an end-to-end test over the mock mcpp | S3 for `view` | +| S5 | Feature code actions: "Enable feature", "Disable feature" as text edits | `tests/cts/lsp` | S2, F7 | +| S7 | Per-kind cleanups in every editor: two commands, the rows `pkg` and `std` | each plugin's test; parity unchanged | F5, S3 | + +**Stream E: the editors.** After the surfaces they stand on. + +| Task | Content | Verified by | Needs | +|---|---|---|---| +| Z0 | Zed's verification with a toy server, on a draft: unverified facts 1 to 4 and 7 | a note appended to this record | approval; nothing else | +| H1 | Helix: the fragment, the README with what was run, the combined language line agreed with X2; the profile `lsp` in `docs/editors.md` for other clients | the fragment parses; unverified facts 5 and 6 settled by hand | S2, S3 | +| Z1 | Zed: the crate, `gen zed` for the tasks, the WebAssembly build in CI, the seventh version statement, `components.tsv`, `release-plan.sh` | the build; no diff in the tasks | S2, S3, S4, Z0 | +| Z2 | Zed in a real editor in CI, after mcppls's | evidence `e2e` in the matrix | Z1 | +| Z3 | Zed's debug locator | a debug session by hand, then in Z2's run | Z1, S4 | +| C1 | Convergence: Neovim's three texts and the page's flowchart read the backend's; CLion's graph falls to a tree of the sections | each plugin's tests; less code in each | S3, F2 | +| C2 | Tier A's flows on `workspace/executeCommand` | each plugin's tests | S2, H1, Z1 | + +**Later, each after a record of its own:** A1, the session with several connections and the +attaching command line (phase 5, after S4); `build.mcpp` in tiers B and C; features of index +packages, when mcpp states them; a context server for Zed's agent. + +### The dependencies + +```mermaid +flowchart LR + X1[X1 mcpp issue] -.-> F7 + F0[F0 gates on a draft] --> F1[F1 threading] & F2[F2 JCEF] + F3[F3 strings] --> F5[F5 cache sections] + F4[F4 scope and level] --> F5 + F6[F6 inline tables] --> F7[F7 local features] + F1 & F2 & F5 & F7 & F8[F8 VS Code pairs] --> F9[F9 series 1.6.0] + F9 --> S0[S0 the matrix] --> S1[S1 surfaces] --> S2[S2 commands over lsp] & S3[S3 documents] + S3 --> S4[S4 command line] + S2 & F7 --> S5[S5 feature actions] + F5 & S3 --> S7[S7 per-kind cleanups] + S2 & S3 --> H1[H1 Helix] + X2[X2 mcppls Helix] -.-> H1 + Z0[Z0 Zed verification] --> Z1 + S2 & S3 & S4 --> Z1[Z1 Zed extension] --> Z2[Z2 Zed in CI] & Z3[Z3 debug locator] + Z1 --> X4[X4 registry entry] + S3 & F2 --> C1[C1 convergence] + S2 & H1 & Z1 --> C2[C2 flows of tier A] + S4 --> A1[A1 attaching] +``` + +A dotted edge is a tie that does not block: F7 lands without the issue's number and gains it, and +H1 lands without mcppls's fragment and links it when it exists. + +- **What can start now, side by side:** X1, X2, X3, F0, F3, F4, F6, F8, Z0. +- **The longest chain:** F0, F1 or F2, F9, S0, S1, S2, Z1, Z2. Everything for Zed and Helix passes + through S1. +- **The first results:** the two crashes of #13 are fixed at F2; Helix works at H1, which is the + first proof of S2 and S3 outside this repository's own tests. + +### The points of decision + +The four points were decided in the review of 2026-11-21, before the work. + +| Point | Decision | +|---|---| +| JCEF on macOS, known after F0 | Whatever F0 shows, F2 is not released ahead. The fixes are released together as series 1.6.0. | +| A graph in Zed, known after Z0 | Zed's own convention decides. Where `window/showDocument` opens a local file it is used; otherwise the graph is opened as Zed opens a file from a task. Nothing is built around a gap of Zed's, and Z3 exists only if a locator works with Zed's own adapters. | +| Tier A's flows on `workspace/executeCommand` (C2) | Done. It is what rule 7 states, a flow is the backend's, and it leaves each plugin the dialog alone. It stays the last task, after H1 and Z1 have run the same flows. | +| The profile `lsp` for other clients, after H1 | Documented as it stands, in `docs/editors.md`: the capabilities read, the commands, the documents, and that only Helix and Zed were run. | + +## Stream F as implemented + +Implemented in series 1.6.0. Where the implementation found a fact this record did not have, the +record above is left as reviewed and the difference is stated here. + +| Task | Difference | +|---|---| +| X1 | posted as [mcpp#992](https://github.com/mcpp-community/mcpp/issues/992); `capabilities/explain` names it as `manifest.packageFeatures`, capability `package-features` | +| F0 | the gate on errors the IDE logs already existed: `reportTestFailure` fails every run on an unclassified error. What no run reached was the path: no document was open when a backend started. The run now restarts the backend with `mcpp.toml` open. The JCEF plugin's id is `com.intellij.modules.jcef`, a plugin built per system and architecture (`262.10968.117-linux-x86_64`). The macOS aarch64 job runs `GraphInteractionTest` (the startup chain and the graphs, in the three JCEF states). The weekly run is the real-IDE run of the latest published plugin; the verifier runs on every change, not weekly. | +| F1 | the reading thread also no longer completes futures. Answers complete on the same sequential thread as the notifications, in the backend's order: on separate threads a listener registered when an answer arrived could miss the notification that followed it (found in review) | +| F2 | a page host extension point, `io.github.mcpp-community.mcpp-clion.pageHost`; `JcefPage` became `WebPage`, with no JCEF import | +| F5 | the inventory states neither the size of `target/` nor whether a legacy cache exists. The project's section shows `target/` without a size, and the legacy cleanup is one of the shared cache's actions, as the command table scopes it. The links are the commands' titles. | +| F6 | a dependency's inline table gets no keys: the snapshot does not list a dependency's keys. A key is offered only after `{` or `,`. The new answers are in `tests/cts/rules/golden/inline-tables.json`; every other position equals 0.9's goldens. | +| F7 | `mcpp.manifest.unknownFeature` takes the severity of `mcpp.toml.diagnostics.unknownKey`; no setting is added. A workspace dependency is read through the nearest enclosing workspace's `[workspace.dependencies]` entry with a `path`. A dependency's features are the names mcpp registers (mcpp's manifest reader): `[features]`'s keys, `default` among them, and the names of `feature-deps`, and under a target selector `feature-requires-abi` and `feature-xlings`. `capabilities/explain` names mcpp#992 and no capability, since no release names one. | +| F6, found in implementing | `app = { ... }` under `[targets]` or `[profile]` was an unknown key to the 0.9 diagnostics while mcpp builds it as `[targets.app]`; it is no longer reported | +| F8 | `contributes.languages` is not generated by `gen vscode`; the configuration is the extension's file `syntaxes/mcpp-toml.language-configuration.json` | +| Neovim | the cache text takes the two sections in this pull request, as "The cache view" states | +| Unverified fact 8 | settled: a stock CLion 2026.2.4.1 on macOS aarch64 gives a plugin JCEF (the graphs are drawn, clicked and recover there), and with the JCEF plugin disabled the tab explains instead of failing. CLion 2026.1 carries JCEF in its core, so its run with the plugin disabled is skipped. | +| Found by the runs | a graph asked within the watcher's poll after the manifest changed was the old manifest's (a defect of 1.5.0 too, met about one run in two); the kept build database is now checked against the manifest's time. On macOS the driver needs each action invoked on the project's frame and the IDE's fixed ports free before an IDE starts. | + +## Sources + +- Zed: [developing extensions](https://zed.dev/docs/extensions/developing-extensions), + [languages](https://zed.dev/docs/extensions/languages), + [debugger extensions](https://zed.dev/docs/extensions/debugger-extensions), + [tasks](https://zed.dev/docs/tasks), + [Mermaid in 0.225.9](https://zed.dev/releases/stable/0.225.9), + [code lenses in 1.1.5](https://zed.dev/releases/stable/1.1.5), + [showDocument, discussion 24852](https://github.com/zed-industries/zed/discussions/24852) and + [53123](https://github.com/zed-industries/zed/discussions/53123), + [panels and web views, issue 21208](https://github.com/zed-industries/zed/issues/21208) +- Helix: [languages.toml](https://docs.helix-editor.com/languages.html), + [commands](https://docs.helix-editor.com/commands.html), + [the plugin system, pull request 8675](https://github.com/helix-editor/helix/pull/8675), + [workspace commands of several servers, issue 9017](https://github.com/helix-editor/helix/issues/9017), + [code lenses, pull request 5063](https://github.com/helix-editor/helix/pull/5063) diff --git a/.github/workflows/clion-stable.yml b/.github/workflows/clion-stable.yml index 44afa71..8aa600b 100644 --- a/.github/workflows/clion-stable.yml +++ b/.github/workflows/clion-stable.yml @@ -9,9 +9,13 @@ on: workflow_dispatch: inputs: release_tag: - description: Published plugin release to install without rebuilding the backend + description: Published plugin release to install without rebuilding the backend (empty, the latest) type: string - default: v0.2.0 + default: '' + # A new CLion is met by CI before a user meets it: the latest published plugin on the stable + # releases named below, every week. + schedule: + - cron: '17 4 * * 1' permissions: contents: read @@ -57,10 +61,14 @@ jobs: if: inputs.plugin_artifact == '' env: GH_TOKEN: ${{ github.token }} - RELEASE_TAG: ${{ inputs.release_tag || 'v0.2.0' }} + RELEASE_TAG: ${{ inputs.release_tag }} run: | set -euo pipefail - [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] + # Unnamed (the weekly run): the newest release that carries the CLion plugin. + if [ -z "$RELEASE_TAG" ]; then + RELEASE_TAG="$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq '[.[] | select((.draft | not) and (.tag_name | test("^(clion-)?v[0-9]+\\.[0-9]+\\.[0-9]+$")))][0].tag_name')" + fi + [[ "$RELEASE_TAG" =~ ^(clion-)?v[0-9]+\.[0-9]+\.[0-9]+$ ]] mkdir -p stable-plugin gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ --pattern 'mcpp-clion-*.zip' --dir stable-plugin @@ -125,7 +133,7 @@ jobs: path: | ${{ runner.temp }}/clion-stable-result/result.json ${{ runner.temp }}/clion-stable-result/checks.json - ${{ runner.temp }}/clion-stable-result/ide-errors.ndjson + ${{ runner.temp }}/clion-stable-result/ide-errors*.ndjson ${{ runner.temp }}/clion-stable-result/settings/result.json ${{ runner.temp }}/clion-stable-result/settings/observations.json ${{ runner.temp }}/clion-stable-result/graphs/result.json @@ -133,4 +141,100 @@ jobs: ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/result.json ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/checks.json ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/no-jcef-window.txt + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/result.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/checks.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/no-jcef-window.txt + if-no-files-found: warn + + # The report of #13 came from macOS on Apple silicon, where the JCEF plugin is a build of its own: + # the startup chain and the graphs (JCEF on, switched off, its plugin disabled) on the newest stable + # CLion there. + # One IDE per runner: on macOS a second IDE started on the same runner could stop at its start, before + # any plugin loads (its log ends at "CPU cores"), and its driver never connected. + runtime-macos: + name: packaged plugin on CLion ${{ matrix.version }} (macOS aarch64, ${{ matrix.scenario }}) + runs-on: macos-15 + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + version: ['2026.2.4.1'] + scenario: [graphRendersNavigatesAndRecoversInJcef, graphExplainsAbsentJcefPlugin, graphExplainsUnavailableJcef] + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup-mcpp + with: + llvm: 'true' + - uses: actions/setup-java@v5 + with: + distribution: temurin + java-version: '25' + - uses: gradle/actions/setup-gradle@v5 + with: + gradle-version: '9.7.1' + - name: The candidate ZIP built once by CI + if: inputs.plugin_artifact != '' + uses: actions/download-artifact@v5 + with: + name: ${{ inputs.plugin_artifact }} + path: stable-plugin + - name: The published ZIP for an isolated release check + if: inputs.plugin_artifact == '' + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.release_tag }} + run: | + set -euo pipefail + if [ -z "$RELEASE_TAG" ]; then + RELEASE_TAG="$(gh api "repos/$GITHUB_REPOSITORY/releases?per_page=100" --jq '[.[] | select((.draft | not) and (.tag_name | test("^(clion-)?v[0-9]+\\.[0-9]+\\.[0-9]+$")))][0].tag_name')" + fi + [[ "$RELEASE_TAG" =~ ^(clion-)?v[0-9]+\.[0-9]+\.[0-9]+$ ]] + mkdir -p stable-plugin + gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --pattern 'mcpp-clion-*.zip' --dir stable-plugin + - name: The pinned language-service plugin + env: + GH_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + version="$(sed -n 's/^mcpplsPluginVersion *= *//p' mide-plugins/clion/gradle.properties)" + gh release download "v$version" --repo Sunrisepeak/mcpp-language-server \ + --pattern "mcppls-clion-$version.zip" --dir stable-plugin + - name: Start the real IDE, complete the startup chain and open the graphs + env: + IDE_VERSION: ${{ matrix.version }} + run: | + set -euo pipefail + plugin="$(find stable-plugin -maxdepth 1 -name 'mcpp-clion-*.zip' -print)" + language="$(find stable-plugin -maxdepth 1 -name 'mcppls-clion-*.zip' -print)" + test -n "$plugin" && test -n "$language" + gradle --no-daemon --max-workers=4 \ + -p mide-plugins/clion/integration-tests test --tests "GraphInteractionTest.${{ matrix.scenario }}" \ + -PpluginZip="$GITHUB_WORKSPACE/$plugin" \ + -PmcpplsZip="$GITHUB_WORKSPACE/$language" \ + -PideVersion="$IDE_VERSION" \ + -Poutput="$RUNNER_TEMP/clion-stable-result" + - uses: actions/upload-artifact@v5 + if: always() + with: + name: clion-stable-macos-${{ matrix.version }}-${{ matrix.scenario }} + # The JUnit results name an assertion's message; the IDE's own log, of a runner's IDE on a + # generated project, names why an IDE did not start. + path: | + ${{ runner.temp }}/clion-stable-result/ide-errors*.ndjson + mide-plugins/clion/integration-tests/build/test-results/test/*.xml + out/ide-tests/tests/*/*/log/idea.log + out/ide-tests/tests/*/*/log/monitoring-thread-dumps-ide/*.txt + ${{ runner.temp }}/clion-stable-result/*/ide-start-retried + ${{ runner.temp }}/clion-stable-result/graphs/result.json + ${{ runner.temp }}/clion-stable-result/graphs/checks.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/result.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/checks.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef/no-jcef-window.txt + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/result.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/checks.json + ${{ runner.temp }}/clion-stable-result/graphs-no-jcef-plugin/no-jcef-window.txt if-no-files-found: warn diff --git a/.gitignore b/.gitignore index b6c05ef..f4d2e55 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ compile_commands.json dist-upload/ .xlings/ out/ide-tests + +# Local reviews and analyses, not design records. +.agents/reviews/ diff --git a/CHANGELOG.md b/CHANGELOG.md index cd9c600..0129979 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,47 @@ The changelog is kept by series (`X.Y`); each section lists its components' releases. +## 1.6 + +### 1.6.0 + +Every component is 1.6.0: the backend, mcpp-vscode, mcpp-clion and mcpp-nvim (from 1.5.0). These +are the fixes of the issue review of 2026-11-21 +([design record](.agents/docs/2026-11-21-editor-surfaces-and-feature-matrix.md), stream F). + +- **CLion: no listener on the reading thread** (#13). "Read access is allowed from inside read-action + only" was logged at startup and each time a backend started. The thread that reads the backend's + output now only decodes frames; notifications reach their listeners in order on a pooled thread, + answers complete on the pool, and the open documents are read in a read action. +- **CLion without JCEF** (#13). Opening a graph without the JCEF plugin failed with + `NoClassDefFoundError: JBCefApp`. The core of the plugin names no JCEF class; JCEF's page host is + registered only when the JCEF plugin is loaded, and without it the tab says why. +- **CLion: the cache tab in the sections of VS Code's page** (#13). Project cache (`target/`) and + Global build cache, each with its cleanups as links on its row and in its context menu; an + ellipsis marks one that asks first. The toolbar keeps Refresh. Neovim's cache text has the same + two sections. +- **CLion: texts read when shown** (#13). Toolbar texts and the Libraries button no longer stay in + English beside Chinese rows. +- **CLion: the runs that would have caught these.** The real-IDE run restarts the backend with + `mcpp.toml` open and checks the cache tab's sections; the graphs run with the JCEF plugin + disabled; the startup chain and the graphs run on macOS aarch64; a weekly run checks the latest + published plugin. The pinned mcppls CLion plugin is 0.23.0. +- **VS Code: pairs and comments in `mcpp.toml`** (#15, #18). Brackets and quotes close as they are + typed, and `#` comments a line. The parity gate keeps every field of each language 0.9.0 + contributed and admits an added one. +- **Inline tables** (#15). Inside `app = { ... }` under `[targets]` the keys of `[targets.app]` are + offered, less those written, and an enum key's values. A dependency's inline table gets nothing: + the snapshot does not list a dependency's keys. +- **A dependency's features** (#16, #17). Inside `features = [...]` of a `path` or workspace + dependency: its features, read from its own `mcpp.toml`; their hover; and + `mcpp.manifest.unknownFeature` for a name it does not declare. An index package's features are not + answered: mcpp states none, and `capabilities/explain` names + [mcpp#992](https://github.com/mcpp-community/mcpp/issues/992) (`manifest.packageFeatures`). +- **A graph right after the manifest changed is the new manifest's.** The kept build database was + dropped by the watcher's next poll (every 500 ms), so a graph asked before it was the old manifest's, + and the page kept it. An entry is now used only while the manifest is the one it was read from. +- **Protocol.** A cache command of `commands/list` states `scope` (`project`, `shared`) and `level`. + ## 1.5 ### 1.5.0 diff --git a/docs/rules.md b/docs/rules.md index c4d6fed..6a0c72f 100644 --- a/docs/rules.md +++ b/docs/rules.md @@ -32,7 +32,9 @@ the order the messages arrive, so an answer sees the document the notifications | On a key of a table with a closed vocabulary | its keys, less those already written in the table's group; a key's detail names its type, values and default | | On a key of a dependency table | the five dependency forms | | On a key of `[features]`, `[generated_files]`, `[capabilities]`, `[xlings.workspace]`, `[tools.overrides]` | that table's forms | -| On an enum key's value | its values (inside a string only the content is replaced) | +| Inside an inline table, after `{` or `,` (1.6.0) | the keys of the table of its name, less those the inline table has on either side of the cursor: `app = { ... }` under `[targets]` lists what `[targets.app]` does, and is not an unknown key of `[targets]`. A dependency's inline table is its specification, whose keys the snapshot does not list, and gets nothing | +| On an enum key's value | its values (inside a string only the content is replaced); a key of an inline table or a dotted key has its own table's | +| Inside `features = [...]` of a dependency given by `path` or `workspace = true` (1.6.0) | the features its own manifest declares and the edge does not name yet, each with whether it is a default and what it implies | | On a dependency's version, with `mcpp.toml.indexCompletion` on and the workspace trusted | the versions mcpp's catalogue (`mcpp search --format json`) lists for that package, newest first; the catalogue is read once in the background (the answer is incomplete until then) and kept for ten minutes | A table is read as the snapshot's section its name denotes: the whole name when the snapshot has @@ -46,11 +48,29 @@ it, its note) and an enum value. Definition jumps from `workspace = true` to the `[workspace.dependencies]`, from an element of `features = [...]` to `[features.]`, and from `path = "../x"` to that manifest's `[package]`. +### A dependency's features + +A dependency's features are read from the text of its own manifest, the rules layer's ground: the +directory its `path` names, or for `workspace = true` the one the nearest enclosing workspace's +`[workspace.dependencies]` entry names. Its features are the names mcpp registers: the keys of +`[features]` (`default` among them) and `[features.]`, and the names of `[feature-deps.]` +and, under a target selector, of `feature-deps`, `feature-requires-abi` and `feature-xlings`. Its +`default` names the ones on without being named, an array or `implies` what each turns on. A +dependency whose manifest declares none accepts any name, as mcpp does. Between two elements a +suggestion brings its commas; an array left open is read on its own line only. + +An index package's features are not answered: mcpp states none +([mcpp#992](https://github.com/mcpp-community/mcpp/issues/992) asks for them), and an index's +descriptors are mcpp's to read. `capabilities/explain` reports this as `manifest.packageFeatures`. +Hover on an element of the edge's `features = [...]` names the dependency, the default and what the +feature implies. + | Code | Default severity | Setting | What it reports | |---|---|---|---| | `mcpp.manifest.syntax` | error | `mcpp.toml.diagnostics.syntax` | a line that is neither a table header nor `key = value`; an invalid key; a key without a value | | `mcpp.manifest.unknownSection` | warning | `mcpp.toml.diagnostics.unknownSection` | a table no section of the snapshot names, nor a prefix of it | | `mcpp.manifest.unknownKey` | warning | `mcpp.toml.diagnostics.unknownKey` | a key a table with a closed vocabulary does not have | +| `mcpp.manifest.unknownFeature` | warning | `mcpp.toml.diagnostics.unknownKey` | a name in a `path` or workspace dependency's `features = [...]` that its manifest's `[features]` does not declare (1.6.0) | | `mcpp.manifest.planeSeparation` | warning | `mcpp.toml.diagnostics.planeSeparation` | a tool payload (`xim:`, `xpm:`, `xlings:`, `xvm:`) as a dependency; an mcpp package with a version under `[xlings]` | | `mcpp.manifest.legacyKey` | info | `mcpp.toml.diagnostics.legacyKeys` | a deprecated table or key, with its replacement | | `mcpp.manifest.mcppFloor` | error | -- | `[package] mcpp` that is not a release floor (`">=2026.9.28.3"`) | @@ -95,3 +115,6 @@ implementation's answers over `tests/cts/rules/corpus` -- the scanner's structur at every position of every line, completion, hover, the jumps, the version contexts and the diagnostics under two sets of severities -- and over the documents of its parser tests (`golden/snippets.json`); the conformance case `rules` (tests/cts/rules.cpp) compares the backend's answers with them. +The answers inside inline tables that 1.6.0 added are where 0.9 answered nothing; they are kept apart, +in `golden/inline-tables.json` (`MCPP_IDE_WRITE_GOLDEN=1 mcpp test cts` writes it again for review), +and every other position still equals 0.9's. diff --git a/mcpp.toml b/mcpp.toml index db96ded..fbdc212 100644 --- a/mcpp.toml +++ b/mcpp.toml @@ -9,7 +9,7 @@ # M2/M3), where the system it runs upon is answered when the image is loaded. [package] name = "mcpp-ide" -version = "1.5.0" +version = "1.6.0" description = "The IDE backend for mcpp: sessions, jobs, records and view models over mcpp's control contract" license = "Apache-2.0" authors = ["mcpp-community"] diff --git a/mide-plugins/clion/README.md b/mide-plugins/clion/README.md index b3fd303..43106ae 100644 --- a/mide-plugins/clion/README.md +++ b/mide-plugins/clion/README.md @@ -78,17 +78,21 @@ backend. The stable IDE tests also use the actual settings dialog: keyboard input, visible validation errors, refusal of partial saves, the persisted XML, reopening the form and restoring defaults. Graph tests inspect the real JCEF document, click a rendered module to open its source, -check visible query errors and recovery, and check the explanation when JCEF is disabled. +check visible query errors and recovery, and check the explanation when JCEF is switched off and +when the JCEF plugin is disabled. The packaged ZIP is also run in the real stable CLion 2026.1.5.2 and 2026.2.4.1 IDEs by `clion-stable.yml`. Both versions load the same ZIP and the pinned mcppls plugin. The test opens an mcpp project, completes protocol 2 initialization, loads runtime translations and commands, -and verifies the visible mcpp tool window and cache inventory. It executes build, run and test +and verifies the visible mcpp tool window and the cache tab's two sections with their cleanups. It +restarts the backend with mcpp.toml open and checks that the document is sent again. It executes build, run and test actions in a project whose path contains Unicode and spaces, launches the native debugger, checks its visible view, source breakpoint, variable values before and after stepping, resume and stop, checks the native test tree, compiler-error output, build/test failure and recovery, and exact manifest completion insertion -during project analysis. It supplements Plugin Verifier's static compatibility checks. +during project analysis. It supplements Plugin Verifier's static compatibility checks. The startup chain and the graphs also +run on macOS aarch64 with CLion 2026.2.4.1, and a weekly run checks the latest published plugin on +the stable releases. CLion 2026.2.4.1 can emit a GDB variable-read cancellation after stopping a debug session; the same exception occurs in a stock CMake project without the plugins. The stable test records the exception class and method symbols, and @@ -99,8 +103,8 @@ An individual packaged plugin can be checked without rebuilding the backend: ```bash xvfb-run -a gradle --no-daemon -p integration-tests test \ - -PpluginZip=/absolute/path/mcpp-clion-1.5.0.zip \ - -PmcpplsZip=/absolute/path/mcppls-clion-0.21.0.zip \ + -PpluginZip=/absolute/path/mcpp-clion-1.6.0.zip \ + -PmcpplsZip=/absolute/path/mcppls-clion-0.23.0.zip \ -PideVersion=2026.1.5.2 ``` diff --git a/mide-plugins/clion/gradle.properties b/mide-plugins/clion/gradle.properties index 91014c7..c8d38d7 100644 --- a/mide-plugins/clion/gradle.properties +++ b/mide-plugins/clion/gradle.properties @@ -2,10 +2,10 @@ # where it installs (2026.1 and later); the verifier checks both ends. platformType = CL platformVersion = 2026.2.3 -pluginVersion = 1.5.0 +pluginVersion = 1.6.0 # The mcppls CLion plugin this one depends on (io.github.sunrisepeak.mcppls): # its release's one package for every system, fetched for the sandbox, the tests and the verifier. -mcpplsPluginVersion = 0.21.0 +mcpplsPluginVersion = 0.23.0 org.gradle.jvmargs = -Xmx2g # The IDE ships the Kotlin standard library; a plugin bundles no second copy. kotlin.stdlib.default.dependency = false diff --git a/mide-plugins/clion/integration-tests/src/test/kotlin/GraphInteractionTest.kt b/mide-plugins/clion/integration-tests/src/test/kotlin/GraphInteractionTest.kt index 74070ee..5998f7c 100644 --- a/mide-plugins/clion/integration-tests/src/test/kotlin/GraphInteractionTest.kt +++ b/mide-plugins/clion/integration-tests/src/test/kotlin/GraphInteractionTest.kt @@ -72,23 +72,50 @@ class GraphInteractionTest { bindSingleton(overrides = true) { object : CIServer by NoCIServer { override fun reportTestFailure(testName: String, message: String, details: String, linkToLogs: String?, kind: SyntheticTestKind, generifyTestName: Boolean) { - throw AssertionError("IDE failure: $testName: $message") + recordIdeFailure("ide-errors-graphs.ndjson", testName, message, details) } } } } } + /** JCEF as the IDE has it: on; switched off (`ide.browser.jcef.enabled=false`); or its plugin + * disabled, so that its classes are absent (#13: `NoClassDefFoundError: JBCefApp`). */ + enum class Jcef(val output: String) { ON("graphs"), SWITCHED_OFF("graphs-no-jcef"), PLUGIN_DISABLED("graphs-no-jcef-plugin") } + + @Test + fun graphRendersNavigatesAndRecoversInJcef() = startingOnce(Jcef.ON) + @Test - fun graphRendersNavigatesAndRecoversInJcef() = runGraphScenario(false) + fun graphExplainsUnavailableJcef() = startingOnce(Jcef.SWITCHED_OFF) @Test - fun graphExplainsUnavailableJcef() = runGraphScenario(true) + fun graphExplainsAbsentJcefPlugin() = startingOnce(Jcef.PLUGIN_DISABLED) - private fun runGraphScenario(disableJcef: Boolean) { + /** + * On a macOS runner an IDE can stop at its start, before any plugin loads (its log ends at "CPU cores"), + * and its driver never connects; it met one run in three, whichever IDE it was. Such a run starts a new + * IDE once, and says so (`ide-start-retried`); a run whose IDE started is never repeated, so a defect of + * this plugin fails it. + */ + private fun startingOnce(jcef: Jcef) { + try { + runGraphScenario(jcef) + } catch (e: Exception) { + val notConnected = generateSequence(e) { it.cause }.any { it.message?.contains("Couldn't wait for the driver to connect") == true } + if (!notConnected) throw e + val output = Path.of(System.getProperty("mcpp.clion.output") ?: "build/stable-smoke").toAbsolutePath().resolve(jcef.output) + Files.createDirectories(output) + Files.writeString(output.resolve("ide-start-retried"), "the first IDE's driver never connected\n") + runGraphScenario(jcef) + } + } + + private fun runGraphScenario(jcef: Jcef) { + val disableJcef = jcef != Jcef.ON val version = System.getProperty("mcpp.clion.ideVersion") ?: error("ideVersion is required") val output = Path.of(System.getProperty("mcpp.clion.output") ?: "build/stable-smoke").toAbsolutePath() - .resolve(if (disableJcef) "graphs-no-jcef" else "graphs") + .resolve(jcef.output) Files.createDirectories(output) val observations = mutableListOf() fun record(name: String) { @@ -115,15 +142,42 @@ class GraphInteractionTest { val context = Starter.newContext("mcpp-graphs-$version-${System.currentTimeMillis()}", TestCase(ide, LocalProjectInfo(fixture))) PluginConfigurator(context).installPluginFromPath(Path.of(System.getProperty("mcpp.clion.mcpplsZip") ?: error("mcpplsZip is required"))) PluginConfigurator(context).installPluginFromPath(Path.of(System.getProperty("mcpp.clion.pluginZip") ?: error("pluginZip is required"))) + // The JCEF plugin is built for each system; an installation can lack it or disable it. CLion + // 2026.1 has no such plugin: JCEF is in the platform's core there, and cannot be absent. + if (jcef == Jcef.PLUGIN_DISABLED) { + val bundled = context.ide.bundledPluginsDir + val jcefPlugin = bundled != null && Files.isDirectory(bundled) && Files.list(bundled).use { dirs -> + dirs.anyMatch { it.fileName.toString().contains("jcef", ignoreCase = true) && Files.isDirectory(it.resolve("lib")) } + } + org.junit.jupiter.api.Assumptions.assumeTrue(jcefPlugin, "CLion $version carries JCEF in its core, not as a plugin") + PluginConfigurator(context).disablePlugins("com.intellij.modules.jcef") + } context.applyVMOptionsPatch { withXmx(2048) addSystemProperty("idea.trust.all.projects", true) addSystemProperty("ide.show.tips.on.startup.default.value", false) // Keep the large generated VFS cache with this isolated test's output. addSystemProperty("idea.system.path", output.resolve("ide-system").toString()) - if (disableJcef) addSystemProperty("ide.browser.jcef.enabled", false) + if (jcef == Jcef.SWITCHED_OFF) addSystemProperty("ide.browser.jcef.enabled", false) + } + // The driver reaches each IDE on fixed ports (JMX 7777, RPC 11111). An IDE that has just closed, or a + // process it started, can hold them for a while; the next IDE could not take them, and its driver + // never connected (macOS aarch64). The run starts when both are free. + for (port in listOf(7777, 11111)) { + val free = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(60) + while (System.nanoTime() < free) { + val bound = runCatching { java.net.ServerSocket().use { it.bind(java.net.InetSocketAddress("127.0.0.1", port)) } }.isSuccess + if (bound) break + Thread.sleep(500) + } } context.runIdeWithDriver().useDriverAndCloseIde { + // An action is invoked on the project's frame: the driver otherwise reads the data context of + // the focused window, which a macOS runner need not give the IDE, and finds no project there. + fun act(id: String) { + val frame = ui.x("//div[@class='IdeFrameImpl']") + invokeAction(id, component = if (frame.present()) frame.component else null) + } waitForProjectOpen() // The IDE settles after the project opens (its layout restored, its startup activities run): a tool // window shown before then can be hidden again by them, on 2026.1 and 2026.2 alike. @@ -156,7 +210,7 @@ class GraphInteractionTest { while (windows.getToolWindow("Project")?.isVisible() != true && System.nanoTime() < restored) Thread.sleep(100) val before = "before the action: project=" + (windows.getToolWindow("Project")?.isVisible() ?: "absent") + " after " + "%.1fs".format((System.nanoTime() - restored) / 1e9 + 60) + "\n" - invokeAction("mcpp.project.showModuleDependencyGraph") + act("mcpp.project.showModuleDependencyGraph") // The sentence wraps in the narrow tool window; its accessible name is whole. val explanation = ui.x("//div[contains(@accessiblename,'This IDE runs without JCEF')]") // Which window is on screen, each time that changes, for the report: the mcpp window @@ -194,7 +248,18 @@ class GraphInteractionTest { } else { val runs = utility().getInstance(singleProject()) val before = runs.getAllDescriptors().map { it.getExecutionId() }.toSet() - invokeAction("mcpp.build") + // The action is enabled once the session knows the project's root; it is invoked on the + // project's frame, which on macOS CI need not hold the focus the driver would read. + val session = service(singleProject()) + val rooted = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30) + while (session.getRoot() == null && System.nanoTime() < rooted) Thread.sleep(100) + val diagnosis = { "root=${session.getRoot()} commands=${session.getCommands().size} frame=${ui.x("//div[@class='IdeFrameImpl']").present()}" } + assertNotNull(session.getRoot(), "the session knows the project's root: ${diagnosis()}") + try { + act("mcpp.build") + } catch (e: Exception) { + throw AssertionError("mcpp.build was not run: ${diagnosis()}", e) + } val deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(180) var finished: RunDescriptorRemote? = null while (System.nanoTime() < deadline) { @@ -210,7 +275,7 @@ class GraphInteractionTest { record("module-project-built") val window = utility().getInstance(singleProject()).getToolWindow("mcpp")!! fun graph(kind: String): GraphCefRemote { - invokeAction(if (kind == "modules") "mcpp.project.showModuleDependencyGraph" else "mcpp.project.showDependencyGraph") + act(if (kind == "modules") "mcpp.project.showModuleDependencyGraph" else "mcpp.project.showDependencyGraph") val expected = if (kind == "modules") "Module Graph" else "Dependency Graph" val ready = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30) while (!window.isVisible() && System.nanoTime() < ready) Thread.sleep(100) @@ -275,6 +340,6 @@ class GraphInteractionTest { val plugin = Path.of(System.getProperty("mcpp.clion.pluginZip")) val sha = java.security.MessageDigest.getInstance("SHA-256").digest(Files.readAllBytes(plugin)).joinToString("") { "%02x".format(it) } val backendControl = System.getProperty("mcpp.clion.backendPath") != null - Files.writeString(output.resolve("result.json"), "{\"ideVersion\":\"$version\",\"pluginSha256\":\"$sha\",\"jcefDisabled\":$disableJcef,\"backendControl\":$backendControl,\"passed\":true}\n") + Files.writeString(output.resolve("result.json"), "{\"ideVersion\":\"$version\",\"pluginSha256\":\"$sha\",\"jcef\":\"${jcef.name.lowercase()}\",\"jcefDisabled\":$disableJcef,\"backendControl\":$backendControl,\"passed\":true}\n") } } diff --git a/mide-plugins/clion/integration-tests/src/test/kotlin/PackagedPluginTest.kt b/mide-plugins/clion/integration-tests/src/test/kotlin/PackagedPluginTest.kt index a9eff6b..5634b50 100644 --- a/mide-plugins/clion/integration-tests/src/test/kotlin/PackagedPluginTest.kt +++ b/mide-plugins/clion/integration-tests/src/test/kotlin/PackagedPluginTest.kt @@ -57,7 +57,16 @@ private fun stockClion262DebuggerStop( "io.github.mcppcommunity." !in reported } -private fun ideFailureFingerprint(message: String, details: String, classification: String): String { +/** An error the IDE logged during a run, kept for the report as its fingerprint, then the run fails. */ +internal fun recordIdeFailure(file: String, testName: String, message: String, details: String): Nothing { + val output = Path.of(System.getProperty("mcpp.clion.output") ?: "build/stable-smoke").toAbsolutePath() + Files.createDirectories(output) + Files.writeString(output.resolve(file), ideFailureFingerprint(message, details, "unclassified") + "\n", + StandardOpenOption.CREATE, StandardOpenOption.APPEND) + throw AssertionError("IDE failure: $testName: $message") +} + +internal fun ideFailureFingerprint(message: String, details: String, classification: String): String { // IDE reports can contain machine paths. Retain only Java/Kotlin type and // method symbols; this is enough to distinguish an SDK error from ours. val text = "$message\n$details" @@ -75,10 +84,21 @@ private fun ideFailureFingerprint(message: String, details: String, classificati @Remote("io.github.mcppcommunity.mcppclion.McppSession", plugin = PLUGIN_ID) interface McppSessionRemote { fun start(): StartupFuture + fun restart() + fun getRoot(): String? fun getCommands(): List fun getDegraded(): Boolean } +@Remote("io.github.mcppcommunity.mcppclion.editor.McppDocuments", plugin = PLUGIN_ID) +interface McppDocumentsRemote { + fun version(uri: String): Int + fun diagnostics(uri: String, version: Int, timeoutMs: Long): RemoteJsonValue? +} + +@Remote("io.github.mcppcommunity.mcppclion.McppSessionKt", plugin = PLUGIN_ID) +interface McppUriFactory { fun uriOf(path: String): String } + @Remote("java.util.concurrent.CompletableFuture") interface StartupFuture { @@ -151,10 +171,17 @@ interface TreeModelRemote { fun getRoot(): TreeNodeRemote } @Remote("javax.swing.tree.DefaultMutableTreeNode") interface TreeNodeRemote { fun getChildAt(index: Int): TreeNodeRemote + fun getChildCount(): Int fun getUserObject(): ViewRowRemote } @Remote("io.github.mcppcommunity.mcppclion.ui.Row", plugin = PLUGIN_ID) -interface ViewRowRemote { fun getError(): Boolean } +interface ViewRowRemote { + fun getText(): String + fun getError(): Boolean + fun getActions(): List +} +@Remote("io.github.mcppcommunity.mcppclion.ui.RowAction", plugin = PLUGIN_ID) +interface RowActionRemote { fun getPlan(): String } @Remote("com.intellij.openapi.project.DumbService") interface DumbServiceFactory { fun getInstance(project: Project): DumbServiceRemote } @Remote("com.intellij.openapi.project.DumbService") @@ -553,6 +580,20 @@ class PackagedPluginTest { assertEquals(manifestBefore + "\n[dependencies]", editor.getDocument().getText(), "completion replaces exactly the requested range") record("manifest-completion-and-insertion") if (indexingAtCompletion) record("manifest-completion-during-indexing") + // A backend that starts again is given every open document again, read in a read action + // off the EDT (#13: "Read access is allowed from inside read-action only" on that path). + // An error the IDE logs on the way fails the run (reportTestFailure above). + val documents = service(singleProject()) + val manifestUri = utility().uriOf(fixture.resolve("mcpp.toml").toString()) + val sentBefore = documents.version(manifestUri) + assertTrue(sentBefore > 0, "the open manifest was sent to the backend") + session.restart() + val restarted = session.start() + val restartDeadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(60) + while (!restarted.isDone() && System.nanoTime() < restartDeadline) Thread.sleep(100) + assertTrue(restarted.isDone(), "the backend starts again") + assertNotNull(documents.diagnostics(manifestUri, sentBefore + 1, 20_000), "the restarted backend is given the open manifest again") + record("open-documents-sent-after-restart") withContext(OnDispatcher.EDT) { val pending = ArrayDeque() pending.add(window.getContentManager().getSelectedContent()!!.getComponent()) @@ -569,8 +610,18 @@ class PackagedPluginTest { val cacheDeadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(15) while (cacheTree!!.getRowCount() == 0 && System.nanoTime() < cacheDeadline) Thread.sleep(100) assertTrue(cacheTree!!.getRowCount() > 0, "opening the cache view loads its inventory without manual refresh") - assertFalse(cacheTree.getModel().getRoot().getChildAt(0).getUserObject().getError(), "the inventory query succeeds") + // The sections of VS Code's page, each cleanup on the one it acts on (#13). + val sections = cacheTree.getModel().getRoot() + assertEquals(2, sections.getChildCount()) + val projectCache = sections.getChildAt(0).getUserObject() + val sharedCache = sections.getChildAt(1) + assertEquals(listOf("stale", "project"), projectCache.getActions().map { it.getPlan() }, "the project's cleanups sit on its section") + assertTrue(sharedCache.getUserObject().getActions().map { it.getPlan() }.containsAll(listOf("cacheGc", "cachePrune", "cacheVerify")), + "the shared cache's cleanups sit on its section") + assertTrue(sharedCache.getChildCount() > 0) + assertFalse(sharedCache.getChildAt(0).getUserObject().getError(), "the inventory query succeeds") record("cache-inventory-visible") + record("cache-sections-with-their-cleanups") } // Store only public versions and assertions. Raw IDE logs can // contain usernames, private paths or workspace details. diff --git a/mide-plugins/clion/integration-tests/src/test/kotlin/SettingsInteractionTest.kt b/mide-plugins/clion/integration-tests/src/test/kotlin/SettingsInteractionTest.kt index 707e8cc..1ba5fd9 100644 --- a/mide-plugins/clion/integration-tests/src/test/kotlin/SettingsInteractionTest.kt +++ b/mide-plugins/clion/integration-tests/src/test/kotlin/SettingsInteractionTest.kt @@ -57,7 +57,7 @@ class SettingsInteractionTest { bindSingleton(overrides = true) { object : CIServer by NoCIServer { override fun reportTestFailure(testName: String, message: String, details: String, linkToLogs: String?, kind: SyntheticTestKind, generifyTestName: Boolean) { - throw AssertionError("IDE failure: $testName: $message") + recordIdeFailure("ide-errors-settings.ndjson", testName, message, details) } } } diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/McppSession.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/McppSession.kt index b3d1760..a23846f 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/McppSession.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/McppSession.kt @@ -168,7 +168,10 @@ class McppSession(private val project: Project) : Disposable { } log.info("mcpp-ide: starting ${located.command.joinToString(" ")} (${located.source})") val b = try { - Backend(located.command + "serve") { line -> log.info("[backend] $line") } + // Notifications and answers in order on one pooled thread (Backend: the reading thread runs + // no listener). + Backend(located.command + "serve", { line -> log.info("[backend] $line") }, + com.intellij.util.concurrency.AppExecutorUtil.createBoundedApplicationPoolExecutor("mcpp-ide events", 1)) } catch (error: Exception) { log.warn("mcpp-ide: startup failed (source=${located.source}, protocol=unknown)", error) future.completeExceptionally(error) diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/backend/Backend.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/backend/Backend.kt index 3cf7492..f873edb 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/backend/Backend.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/backend/Backend.kt @@ -3,6 +3,11 @@ // are named; mcpp-ide's own are under `mcpp-ide/`, which this class adds to a request and takes off // a notification. Requests answer futures; notifications go to the listeners of their method ("*" // receives every one). +// +// The thread that reads the backend's output only decodes frames: a notification's listeners and a +// request's answer run on `events`, one at a time and in the order the backend wrote them, so what +// continues after an answer (a listener it registers, the output it buffered) runs before the next +// message. A listener that reads the IDE's model therefore never runs on the reading thread (#13). package io.github.mcppcommunity.mcppclion.backend import com.google.gson.JsonElement @@ -16,6 +21,8 @@ import java.nio.charset.StandardCharsets import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CopyOnWriteArrayList +import java.util.concurrent.Executor +import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger @@ -73,7 +80,14 @@ fun wireName(method: String): String = method.startsWith(NAMESPACE)) method else NAMESPACE + method -class Backend(command: List, private val log: (String) -> Unit = {}) : AutoCloseable { +/** One daemon thread, for the notifications of a backend run without the IDE's executors (the tests). */ +fun sequentialExecutor(name: String): Executor = Executors.newSingleThreadExecutor { r -> Thread(r, name).apply { isDaemon = true } } + +class Backend( + command: List, + private val log: (String) -> Unit = {}, + private val events: Executor = sequentialExecutor("mcpp-ide events"), +) : AutoCloseable { private val process: Process = ProcessBuilder(command).redirectErrorStream(false).start() private val input: OutputStream = process.outputStream private val pending = ConcurrentHashMap>>() @@ -92,9 +106,13 @@ class Backend(command: List, private val log: (String) -> Unit = {}) : A thread("mcpp-ide exit") { process.waitFor() val ended = BackendError("", -32099, "the mcpp-ide backend ended", null) - pending.values.forEach { it.second.completeExceptionally(ended) } + val waiting = pending.values.toList() pending.clear() - exited.complete(process.exitValue()) + val code = process.exitValue() + events.execute { + waiting.forEach { it.second.completeExceptionally(ended) } + exited.complete(code) + } } } @@ -117,14 +135,20 @@ class Backend(command: List, private val log: (String) -> Unit = {}) : A val (method, future) = pending.remove(id.asInt) ?: return if (message.has("error")) { val e = message.getAsJsonObject("error") - future.completeExceptionally(BackendError(method, e.get("code")?.asInt ?: -32603, e.get("message")?.asString ?: "failed", e.get("data"))) - } else future.complete(message.get("result") ?: JsonNull.INSTANCE) + val error = BackendError(method, e.get("code")?.asInt ?: -32603, e.get("message")?.asString ?: "failed", e.get("data")) + events.execute { future.completeExceptionally(error) } + } else { + val result = message.get("result") ?: JsonNull.INSTANCE + events.execute { future.complete(result) } + } return } val method = message.get("method")?.asString?.removePrefix(NAMESPACE) ?: return val params = message.get("params") ?: JsonObject() - listeners[method]?.forEach { runCatching { it(method, params) }.onFailure { e -> log("$method: ${e.message}") } } - listeners["*"]?.forEach { runCatching { it(method, params) } } + events.execute { + listeners[method]?.forEach { runCatching { it(method, params) }.onFailure { e -> log("$method: ${e.message}") } } + listeners["*"]?.forEach { runCatching { it(method, params) } } + } } fun request(method: String, params: JsonElement = JsonObject()): CompletableFuture { diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/editor/McppEditor.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/editor/McppEditor.kt index 1d69887..ba31d63 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/editor/McppEditor.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/editor/McppEditor.kt @@ -107,10 +107,16 @@ class McppDocuments(private val project: Project) : Disposable { reopen() } + /** Sends every open document again. It is called from the startup activity and when a backend + * has started, off the EDT: the documents are read in a read action (#13). */ private fun reopen() { sent.clear() - for (file in FileEditorManager.getInstance(project).openFiles) - if (served(file)) FileDocumentManager.getInstance().getDocument(file)?.let { sync(file, it) } + val open = com.intellij.openapi.application.ApplicationManager.getApplication().runReadAction(com.intellij.openapi.util.Computable { + if (project.isDisposed) emptyList>() + else FileEditorManager.getInstance(project).openFiles.filter { served(it) } + .mapNotNull { file -> FileDocumentManager.getInstance().getDocument(file)?.let { file to it } } + }) + for ((file, document) in open) sync(file, document) } /** Sends the document's text when it differs from what the backend holds: its uri and version. */ @@ -164,6 +170,9 @@ class McppDocuments(private val project: Project) : Disposable { } } + /** The version of a document last sent to the backend; 0 when it was never sent (the IDE runs read it). */ + fun version(uri: String): Int = versions[uri] ?: 0 + /** The diagnostics the backend published for `version` of the document or a later one. */ fun diagnostics(uri: String, version: Int, timeoutMs: Long): JsonArray? { published[uri]?.let { p -> if ((p["version"]?.takeIf { !it.isJsonNull }?.asInt ?: 0) >= version) return p.getAsJsonArray("diagnostics") } diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/CacheView.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/CacheView.kt index 72cdd48..f0d89f8 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/CacheView.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/CacheView.kt @@ -1,16 +1,16 @@ -// The cache: what mcpp keeps (`cache/inventory` over `mcpp cache list`) -- the total, each kind and -// its size, the largest labels, the ages -- and the cleanups of the command table, each planned, -// confirmed at its danger level and applied as a job (Dispatch.cleanup). +// The cache, in the two sections of VS Code's page (design 2026-11-21, "The cache view"): the +// project's build (`target/`) with its cleanups, and the shared cache mcpp keeps (`cache/inventory` +// over `mcpp cache list`) -- the total, each kind and its size, the largest labels, the ages -- with +// its own. A cleanup sits on the section it acts on, by the scope the command table states, and is +// planned, confirmed at its danger level and applied as a job (Dispatch.cleanup). package io.github.mcppcommunity.mcppclion.ui import com.google.gson.JsonObject import com.intellij.icons.AllIcons import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager -import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.application.ApplicationManager -import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.util.Disposer @@ -23,13 +23,46 @@ import javax.swing.JComponent import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel -/** The cache's rows, from the inventory. Pure: the tests build it. */ +/** The cache's sections, from the command table and the inventory. Pure: the tests build it. */ object CacheModel { + /** + * The cleanups the command table states for a scope (`project`, `shared`), in its order, one per + * plan: two commands of one plan (mcpp.clean, mcpp.cleanProjectArtifacts) are one action, the + * cache group's, in its place. + */ + fun actions(commands: List, scope: String): List { + val byPlan = linkedMapOf() + for (c in commands) { + val action = c["action"]?.takeIf { it.isJsonObject }?.asJsonObject ?: continue + if (action["kind"]?.asString != "cache" || action["scope"]?.asString != scope) continue + val plan = action["plan"]?.asString ?: continue + val kept = byPlan[plan] + if (kept == null || (kept["group"]?.asString != "cache" && c["group"]?.asString == "cache")) byPlan[plan] = c + } + return byPlan.entries.sortedBy { (_, c) -> commands.indexOf(c) }.map { (plan, c) -> + RowAction(c["id"].asString, plan, c["title"]?.asString ?: plan, (c["action"].asJsonObject["level"]?.asInt ?: 0) > 0) + } + } + + fun sections(inventory: JsonObject?, error: String?, commands: List, t: (String, Array) -> String): List { + fun tr(key: String, vararg a: Any?) = t(key, a) + val project = RowNode(Row(tr("Project cache"), "target/", AllIcons.Nodes.Module, actions = actions(commands, "project"))) + val shared = mutableListOf() + var total = "" + if (error != null) shared += RowNode(Row(tr("mcpp: {0}", error), icon = AllIcons.General.Error, error = true)) + else if (inventory != null) { + total = tr("{0} in {1} entries", inventory["totalText"]?.asString ?: "", inventory["totalEntries"]?.asString ?: "0") + shared += rows(inventory, t) + } + val cache = RowNode(Row(tr("Global build cache"), total, AllIcons.Nodes.Folder, actions = actions(commands, "shared")), shared) + return listOf(project, cache) + } + + /** What the inventory says of the shared cache: where it is, each kind, the largest, the ages. */ fun rows(inventory: JsonObject, t: (String, Array) -> String): List { fun tr(key: String, vararg a: Any?) = t(key, a) val out = mutableListOf() - out += RowNode(Row(tr("{0} in {1} entries", inventory["totalText"]?.asString ?: "", inventory["totalEntries"]?.asString ?: "0"), - inventory["root"]?.asString ?: "", AllIcons.Nodes.Folder)) + inventory["root"]?.asString?.takeIf { it.isNotEmpty() }?.let { out += RowNode(Row(it, icon = AllIcons.Nodes.Folder)) } val kinds = inventory["byKind"].objects() if (kinds.isNotEmpty()) out += RowNode(Row(tr("By kind"), icon = AllIcons.Nodes.Folder), kinds.map { k -> @@ -59,7 +92,6 @@ class CacheView(private val project: Project, parent: Disposable) : McppView, Di private val session = McppSession.get(project) private val tree = Tree(DefaultTreeModel(DefaultMutableTreeNode())) private val panel = SimpleToolWindowPanel(true, true) - private val cleanups = DefaultActionGroup() val component: JComponent get() = panel private var unsubscribe: () -> Unit = {} @@ -68,12 +100,10 @@ class CacheView(private val project: Project, parent: Disposable) : McppView, Di tree.isRootVisible = false tree.showsRootHandles = true tree.cellRenderer = RowRenderer() + installRowActions(tree) { a -> Dispatch.cleanup(project, a.plan) } + // The toolbar holds what acts on the whole view; each cleanup is its section's. val group = DefaultActionGroup().apply { - add(object : DumbAwareAction(session.t("Refresh"), null, AllIcons.Actions.Refresh) { - override fun actionPerformed(e: AnActionEvent) = refresh() - }) - addSeparator() - add(cleanups) + add(SessionAction({ session.t("Refresh") }, AllIcons.Actions.Refresh) { refresh() }) } val toolbar = ActionManager.getInstance().createActionToolbar("McppCacheView", group, true) toolbar.targetComponent = panel @@ -82,30 +112,17 @@ class CacheView(private val project: Project, parent: Disposable) : McppView, Di unsubscribe = session.on("job/finished") { p -> if (p.asJsonObject["kind"]?.asString in setOf("cache", "clean", "command")) refresh() } } - /** The cleanups the command table offers here, under their titles. */ - private fun fillCleanups() { - cleanups.removeAll() - for (c in session.commands) { - val action = c["action"]?.asJsonObject ?: continue - if (action["kind"]?.asString != "cache") continue - val plan = action["plan"]?.asString ?: continue - cleanups.add(object : DumbAwareAction(c["title"]?.asString ?: plan, null, AllIcons.Actions.GC) { - override fun actionPerformed(e: AnActionEvent) = Dispatch.cleanup(project, plan) - }) - } - } - override fun refresh() { if (!session.running) return session.request("cache/inventory", JsonObject().apply { session.root?.let { addProperty("root", it) } }).whenComplete { r, error -> ApplicationManager.getApplication().invokeLater { if (project.isDisposed) return@invokeLater - fillCleanups() val root = DefaultMutableTreeNode() - if (error != null) root.add(RowNode(Row(session.t("mcpp: {0}", (error.cause ?: error).message ?: ""), icon = AllIcons.General.Error, error = true))) - else CacheModel.rows(r.asJsonObject) { key, args -> session.t(key, *args) }.forEach { root.add(it) } + val failed = error?.let { (it.cause ?: it).message ?: "" } + CacheModel.sections(r?.takeIf { it.isJsonObject }?.asJsonObject, failed, session.commands) { key, args -> session.t(key, *args) } + .forEach { root.add(it) } tree.model = DefaultTreeModel(root) - TreeUtil.expand(tree, 1) + TreeUtil.expand(tree, 2) } } } diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/GraphPage.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/GraphPage.kt index bc23453..d4e85c4 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/GraphPage.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/GraphPage.kt @@ -9,13 +9,12 @@ import com.google.gson.JsonObject import com.google.gson.JsonParser import com.intellij.openapi.project.Project import com.intellij.ui.JBColor -import io.github.mcppcommunity.mcppclion.McppSession class GraphPage(project: Project, private val kind: String) : - JcefPage(project, "graph.html", McppSession.get(project).t("This IDE runs without JCEF, which draws the graph.")) { + WebPage(project, "graph.html", "This IDE runs without JCEF, which draws the graph.") { override val id = "graph:$kind" - override fun refresh() { + override fun draw() { val root = session.root ?: return session.request("graph/$kind", JsonObject().apply { addProperty("root", root) }).whenComplete { graph, error -> show(JsonObject().apply { diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/LibraryView.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/LibraryView.kt index d8d8722..3ab9c14 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/LibraryView.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/LibraryView.kt @@ -134,6 +134,8 @@ class LibraryView(private val project: Project, parent: Disposable) : McppView, } override fun refresh() { + // Read when shown: the view is built before the session's strings arrive (#13). + add.text = session.t("Add to the project") if (!session.running) return val params = JsonObject().apply { addProperty("keyword", search.text.trim()) diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/PageHost.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/PageHost.kt new file mode 100644 index 0000000..4fdd032 --- /dev/null +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/PageHost.kt @@ -0,0 +1,32 @@ +// The browser a page of webui/ is drawn in, as the core of the plugin knows it: a component, a page +// to load, a script to run in it, and what the page sends back. The core names no browser. JCEF's +// host (ui/jcef) is registered only by mcpp-jcef.xml, which the platform reads when the JCEF plugin +// is loaded, so a CLion without that plugin never links JCEF's classes; with no host, or a host +// that cannot draw now (JCEF switched off), the page's tab says why (#13). +package io.github.mcppcommunity.mcppclion.ui + +import com.intellij.openapi.Disposable +import com.intellij.openapi.extensions.ExtensionPointName +import javax.swing.JComponent + +interface PageHost : Disposable { + val component: JComponent + fun load(url: String) + /** Runs a script in the page that is loaded. */ + fun execute(script: String) +} + +interface PageHostFactory { + /** + * A host, or null when this IDE cannot draw a page now. `received` gets what the page sends + * (`mcppHostSend`); `loaded` runs on the EDT each time the page has loaded. + */ + fun create(received: (String) -> Unit, loaded: () -> Unit): PageHost? + + companion object { + val EP: ExtensionPointName = ExtensionPointName.create("io.github.mcpp-community.mcpp-clion.pageHost") + + fun create(received: (String) -> Unit, loaded: () -> Unit): PageHost? = + EP.extensionList.firstNotNullOfOrNull { runCatching { it.create(received, loaded) }.getOrNull() } + } +} diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/ProjectView.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/ProjectView.kt index f4f3fa0..4b7dc61 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/ProjectView.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/ProjectView.kt @@ -34,9 +34,17 @@ import javax.swing.JTree import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel -/** A row of a tree: its text, a quieter detail, an icon, and a file it opens or a command it runs. */ +/** A row of a tree: its text, a quieter detail, an icon, a file it opens or a command it runs, and the + * actions on what it shows, drawn as links after its detail and listed in its context menu. */ data class Row(val text: String, val detail: String = "", val icon: Icon? = null, val file: String? = null, - val command: String? = null, val root: String? = null, val error: Boolean = false) + val command: String? = null, val root: String? = null, val error: Boolean = false, + val actions: List = emptyList()) + +/** An action of a row: a cleanup of the command table, by its title; `asks` when it confirms first. */ +data class RowAction(val command: String, val plan: String, val title: String, val asks: Boolean) { + /** The link's text: an ellipsis marks an action that asks before it acts. */ + val label: String get() = if (asks) "$title…" else title +} /** A row with its children. */ class RowNode(row: Row, children: List = emptyList()) : DefaultMutableTreeNode(row) { @@ -137,9 +145,7 @@ class ProjectView(private val project: Project, parent: Disposable) : McppView, .map { m -> session.on(m) { refresh() } } } - private fun action(text: String, icon: Icon, run: () -> Unit) = object : DumbAwareAction(session.t(text), null, icon) { - override fun actionPerformed(e: AnActionEvent) = run() - } + private fun action(text: String, icon: Icon, run: () -> Unit) = SessionAction({ session.t(text) }, icon, run) private fun open(row: Row) { row.file?.let { path -> @@ -186,14 +192,73 @@ class ProjectView(private val project: Project, parent: Disposable) : McppView, } } -/** A row's text, then its detail in grey; an error in the error colour. */ +/** + * A toolbar action whose text is read each time the toolbar shows it: a view is built before the + * session's strings (`i18n/bundle`) arrive, so a text read once would stay in English (#13). + */ +class SessionAction(private val text: () -> String, icon: Icon, private val run: () -> Unit) : + DumbAwareAction(text(), null, icon) { + override fun getActionUpdateThread() = com.intellij.openapi.actionSystem.ActionUpdateThread.BGT + override fun update(e: AnActionEvent) { + e.presentation.text = text() + } + override fun actionPerformed(e: AnActionEvent) = run() +} + +/** A row's text, then its detail in grey, then its actions as links; an error in the error colour. */ class RowRenderer : ColoredTreeCellRenderer() { override fun customizeCellRenderer(tree: JTree, value: Any?, selected: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean) { val r = (value as? RowNode)?.row ?: return icon = r.icon append(r.text, if (r.error) SimpleTextAttributes.ERROR_ATTRIBUTES else SimpleTextAttributes.REGULAR_ATTRIBUTES) if (r.detail.isNotEmpty()) append(" " + r.detail, SimpleTextAttributes.GRAYED_ATTRIBUTES) + for ((i, a) in r.actions.withIndex()) { + append(if (i == 0) " " else " ", SimpleTextAttributes.REGULAR_ATTRIBUTES) + append(a.label, SimpleTextAttributes.LINK_ATTRIBUTES, a) + } + } +} + +/** + * A row's actions in a tree: a click on a link runs it, the pointer shows a hand over one, and the + * row's context menu lists them (with the keyboard's context-menu key too). + */ +fun installRowActions(tree: JTree, run: (RowAction) -> Unit) { + fun actionAt(e: MouseEvent): RowAction? { + val path = tree.getPathForLocation(e.x, e.y) ?: return null + val bounds = tree.getPathBounds(path) ?: return null + val node = path.lastPathComponent as? RowNode ?: return null + if (node.row.actions.isEmpty()) return null + val row = tree.getRowForPath(path) + val renderer = tree.cellRenderer.getTreeCellRendererComponent(tree, node, false, tree.isExpanded(path), node.isLeaf, row, false) + val colored = renderer as? com.intellij.ui.SimpleColoredComponent ?: return null + colored.setBounds(0, 0, bounds.width, bounds.height) + val fragment = colored.findFragmentAt(e.x - bounds.x) + return if (fragment >= 0) colored.getFragmentTag(fragment) as? RowAction else null + } + val mouse = object : java.awt.event.MouseAdapter() { + override fun mouseClicked(e: MouseEvent) { + if (e.button != MouseEvent.BUTTON1 || e.clickCount != 1) return + actionAt(e)?.let { e.consume(); run(it) } + } + override fun mouseMoved(e: MouseEvent) { + tree.cursor = if (actionAt(e) != null) java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.HAND_CURSOR) else null + } + } + tree.addMouseListener(mouse) + tree.addMouseMotionListener(mouse) + val menu = object : com.intellij.openapi.actionSystem.ActionGroup() { + override fun getActionUpdateThread() = com.intellij.openapi.actionSystem.ActionUpdateThread.EDT + override fun getChildren(e: AnActionEvent?): Array { + val node = tree.selectionPath?.lastPathComponent as? RowNode ?: return emptyArray() + return node.row.actions.map { a -> + object : DumbAwareAction(a.label) { + override fun actionPerformed(e: AnActionEvent) = run(a) + } + }.toTypedArray() + } } + com.intellij.ui.PopupHandler.installPopupMenu(tree, menu, "McppRowActions") } /** The values of a JSON array as objects. */ diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/TestsPage.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/TestsPage.kt index 24a6e38..34e75ad 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/TestsPage.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/TestsPage.kt @@ -11,7 +11,7 @@ import com.intellij.ui.JBColor import io.github.mcppcommunity.mcppclion.McppSession class TestsPage(project: Project) : - JcefPage(project, "tests.html", McppSession.get(project).t("This IDE runs without JCEF, which draws the test insights.")) { + WebPage(project, "tests.html", "This IDE runs without JCEF, which draws the test insights.") { override val id = "tests" private val unsubscribe = session.on("job/finished") { p -> if (p.isJsonObject && p.asJsonObject["kind"]?.asString == "test") refresh() @@ -37,7 +37,7 @@ class TestsPage(project: Project) : addProperty("noMetrics", session.t("Metrics appear when the project's mcpp states them (test-metrics, mcpp#917).")) } - override fun refresh() { + override fun draw() { val root = session.root ?: return session.request("test/insights", JsonObject().apply { addProperty("root", root) }).whenComplete { insights, _ -> if (insights == null || !insights.isJsonObject) return@whenComplete diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/JcefPage.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/WebPage.kt similarity index 54% rename from mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/JcefPage.kt rename to mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/WebPage.kt index 2b19a71..7df1503 100644 --- a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/JcefPage.kt +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/WebPage.kt @@ -1,7 +1,8 @@ -// A page of webui/ in JCEF (mcpp design 2026-10-30 part 2 §9): the plugin's copy of the page's files, -// a browser that loads one of them, `mcppRender` to hand the page the backend's answer and its strings, -// and `mcppHostSend` for what the page asks of the IDE. A page reaches nothing else. Without JCEF the -// tab says why. +// A page of webui/ (mcpp design 2026-10-30 part 2 §9): the plugin's copy of the page's files, a page +// host that loads one of them, `mcppRender` to hand the page the backend's answer and its strings, and +// `mcppHostSend` for what the page asks of the IDE. A page reaches nothing else. The host is the +// browser the IDE gives (PageHost.kt); without one the tab says why, in the session's language when +// it is shown. package io.github.mcppcommunity.mcppclion.ui import com.google.gson.JsonObject @@ -13,54 +14,52 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.ui.components.JBTextArea -import com.intellij.ui.jcef.JBCefApp -import com.intellij.ui.jcef.JBCefBrowser -import com.intellij.ui.jcef.JBCefBrowserBase -import com.intellij.ui.jcef.JBCefJSQuery import com.intellij.util.ui.JBUI import io.github.mcppcommunity.mcppclion.McppSession -import org.cef.browser.CefBrowser -import org.cef.browser.CefFrame -import org.cef.handler.CefLoadHandlerAdapter import java.io.File import javax.swing.JComponent -abstract class JcefPage(protected val project: Project, private val file: String, withoutJcef: String) : McppView, Disposable { +abstract class WebPage(protected val project: Project, private val file: String, private val withoutBrowser: String) : McppView, Disposable { protected val session = McppSession.get(project) - private val browser: JBCefBrowser? = if (JBCefApp.isSupported()) JBCefBrowser() else null - private val query: JBCefJSQuery? = browser?.let { JBCefJSQuery.create(it as JBCefBrowserBase) } @Volatile private var loaded = false private var pending: String? = null - // Without JCEF the page says why. The tool window sits on the left beside Project, narrower than + private val host: PageHost? = PageHostFactory.create({ text -> received(text) }) { + loaded = true + pending?.let { render(it) } + pending = null + } + // Without a host the page says why. The tool window sits on the left beside Project, narrower than // the sentence, so the text wraps; its accessible name is the whole sentence. - val component: JComponent = browser?.component ?: unavailable(withoutJcef) + private val explanation: JBTextArea? = if (host == null) unavailable(session.t(withoutBrowser)) else null + val component: JComponent = host?.component ?: explanation!! init { - if (browser != null && query != null) { - Disposer.register(this, browser) - Disposer.register(this, query) - query.addHandler { text -> received(text); null } - browser.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() { - override fun onLoadEnd(b: CefBrowser, frame: CefFrame, status: Int) { - if (!frame.isMain) return - b.executeJavaScript("window.mcppHostSend = function (text) { ${query.inject("text")} };", b.url, 0) - ApplicationManager.getApplication().invokeLater { - loaded = true - pending?.let { render(it) } - pending = null - } - } - }, browser.cefBrowser) - browser.loadURL(page().toURI().toString()) + host?.let { + Disposer.register(this, it) + it.load(page().toURI().toString()) } } /** What the page sent (`mcppHostSend`). */ protected abstract fun received(text: String) + /** Asks the backend for what the page draws and hands it to [show]. */ + protected abstract fun draw() + + /** Called on any thread (a job's end refreshes the tests' page). */ + final override fun refresh() { + explanation?.let { + ApplicationManager.getApplication().invokeLater { + it.text = session.t(withoutBrowser) + it.accessibleContext.accessibleName = it.text + } + } + if (host != null) draw() + } + /** The page's files, written once per build of the plugin where the browser can load them. */ private fun page(): File { - val jar = runCatching { File(JcefPage::class.java.protectionDomain.codeSource.location.toURI()) }.getOrNull() + val jar = runCatching { File(WebPage::class.java.protectionDomain.codeSource.location.toURI()) }.getOrNull() val version = jar?.takeIf { it.isFile }?.let { "${it.nameWithoutExtension}-${it.lastModified()}" } ?: "dev" val dir = File(PathManager.getSystemPath(), "mcpp-clion/webui-$version") val index = javaClass.getResource("/webui/files.txt")?.readText() ?: error("the pages are not in the plugin (webui/files.txt)") @@ -82,8 +81,7 @@ abstract class JcefPage(protected val project: Project, private val file: String } private fun render(page: String) { - val b = browser ?: return - b.cefBrowser.executeJavaScript("window.mcppRender && window.mcppRender($page);", b.cefBrowser.url, 0) + host?.execute("window.mcppRender && window.mcppRender($page);") } /** A file of the project in an editor, at a 0-based line. */ @@ -98,7 +96,7 @@ abstract class JcefPage(protected val project: Project, private val file: String override fun dispose() {} } -private fun unavailable(text: String): JComponent = JBTextArea(text).apply { +private fun unavailable(text: String): JBTextArea = JBTextArea(text).apply { isEditable = false lineWrap = true wrapStyleWord = true diff --git a/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/jcef/JcefPageHost.kt b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/jcef/JcefPageHost.kt new file mode 100644 index 0000000..d2fa918 --- /dev/null +++ b/mide-plugins/clion/src/main/kotlin/io/github/mcppcommunity/mcppclion/ui/jcef/JcefPageHost.kt @@ -0,0 +1,49 @@ +// JCEF's page host: a JBCefBrowser, a query the page's `mcppHostSend` reaches, and a load handler +// that injects it. This package is the only one that names JCEF's classes; mcpp-jcef.xml registers +// its factory, and the platform reads that file only when the JCEF plugin is loaded (PageHost.kt). +package io.github.mcppcommunity.mcppclion.ui.jcef + +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.util.Disposer +import com.intellij.ui.jcef.JBCefApp +import com.intellij.ui.jcef.JBCefBrowser +import com.intellij.ui.jcef.JBCefBrowserBase +import com.intellij.ui.jcef.JBCefJSQuery +import io.github.mcppcommunity.mcppclion.ui.PageHost +import io.github.mcppcommunity.mcppclion.ui.PageHostFactory +import org.cef.browser.CefBrowser +import org.cef.browser.CefFrame +import org.cef.handler.CefLoadHandlerAdapter +import javax.swing.JComponent + +class JcefPageHost private constructor(received: (String) -> Unit, loaded: () -> Unit) : PageHost { + private val browser = JBCefBrowser() + private val query = runCatching { JBCefJSQuery.create(browser as JBCefBrowserBase) } + .onFailure { Disposer.dispose(browser) }.getOrThrow() + override val component: JComponent get() = browser.component + + init { + Disposer.register(this, browser) + Disposer.register(this, query) + query.addHandler { text -> received(text); null } + browser.jbCefClient.addLoadHandler(object : CefLoadHandlerAdapter() { + override fun onLoadEnd(b: CefBrowser, frame: CefFrame, status: Int) { + if (!frame.isMain) return + b.executeJavaScript("window.mcppHostSend = function (text) { ${query.inject("text")} };", b.url, 0) + ApplicationManager.getApplication().invokeLater { loaded() } + } + }, browser.cefBrowser) + } + + override fun load(url: String) = browser.loadURL(url) + + override fun execute(script: String) = browser.cefBrowser.executeJavaScript(script, browser.cefBrowser.url, 0) + + override fun dispose() {} + + /** No host while JCEF is switched off (`ide.browser.jcef.enabled=false`) or cannot start here. */ + class Factory : PageHostFactory { + override fun create(received: (String) -> Unit, loaded: () -> Unit): PageHost? = + if (JBCefApp.isSupported()) JcefPageHost(received, loaded) else null + } +} diff --git a/mide-plugins/clion/src/main/resources/META-INF/mcpp-jcef.xml b/mide-plugins/clion/src/main/resources/META-INF/mcpp-jcef.xml index c389eb5..0f9b2d3 100644 --- a/mide-plugins/clion/src/main/resources/META-INF/mcpp-jcef.xml +++ b/mide-plugins/clion/src/main/resources/META-INF/mcpp-jcef.xml @@ -1,2 +1,6 @@ - - + + + + + + diff --git a/mide-plugins/clion/src/main/resources/META-INF/plugin.xml b/mide-plugins/clion/src/main/resources/META-INF/plugin.xml index e82a0b2..dc755aa 100644 --- a/mide-plugins/clion/src/main/resources/META-INF/plugin.xml +++ b/mide-plugins/clion/src/main/resources/META-INF/plugin.xml @@ -21,14 +21,22 @@ com.intellij.modules.clion com.intellij.modules.cidr.debugger io.github.sunrisepeak.mcppls - + com.intellij.modules.jcef intellij.testRunner.plugin + + + + + + val body = """{"jsonrpc":"2.0","method":"mcpp-ide/job/progress","params":{"n":$n}}""" + "Content-Length: ${body.toByteArray().size}\r\n\r\n$body" + } + val script = Files.createTempFile("mcppclion-frames-", ".sh").toFile() + // The frames are written once the listener is in place. + script.writeText("sleep 1\nprintf '%s' '$frames'\nsleep 2\n") + val threads = java.util.Collections.synchronizedList(mutableListOf()) + val order = java.util.Collections.synchronizedList(mutableListOf()) + val done = CompletableFuture() + Backend(listOf("sh", script.path), {}, io.github.mcppcommunity.mcppclion.backend.sequentialExecutor("test events")).use { backend -> + backend.on("job/progress") { _, p -> + threads += Thread.currentThread().name + order += p.asJsonObject["n"].asInt + if (order.size == 3) done.complete(Unit) + } + done.get(10, TimeUnit.SECONDS) + } + assertEquals(listOf(1, 2, 3), order.toList()) + assertTrue(threads.toString(), threads.all { it == "test events" }) + } + @Test fun theBundleRunsUnderTheOkrunCarriedForThisSystem() { assertEquals("windows-x86_64", Locate.okrunDir("Windows 11", "amd64")) diff --git a/mide-plugins/clion/src/test/kotlin/io/github/mcppcommunity/mcppclion/UiTest.kt b/mide-plugins/clion/src/test/kotlin/io/github/mcppcommunity/mcppclion/UiTest.kt index 5e205c9..0d30a4a 100644 --- a/mide-plugins/clion/src/test/kotlin/io/github/mcppcommunity/mcppclion/UiTest.kt +++ b/mide-plugins/clion/src/test/kotlin/io/github/mcppcommunity/mcppclion/UiTest.kt @@ -67,16 +67,70 @@ class UiTest { } @Test - fun theCacheRowsFromTheInventory() { + fun theCacheInTheSectionsOfVsCodesPage() { val inventory = json("""{"root": "/home/u/.mcpp", "totalBytes": 3, "totalEntries": 2, "totalText": "1.5 GiB", "byKind": [{"kind": "bmi", "entries": 2, "bytes": 3, "bytesText": "1.5 GiB"}], "topLabels": [{"label": "std", "entries": 1, "bytes": 2, "bytesText": "1.0 GiB"}], "ageBuckets": [{"fromDays": 0, "toDays": 7, "entries": 2, "bytes": 3, "bytesText": "1.5 GiB"}, {"fromDays": 7, "entries": 0, "bytes": 0, "bytesText": "0 B"}], "incomplete": []}""") - val rows = CacheModel.rows(inventory, t) - assertEquals(listOf("1.5 GiB in 2 entries", "By kind", "Largest", "By last use"), rows.map { it.row.text }) - assertEquals("0–7 days", (rows[3].getChildAt(0) as RowNode).row.text) - assertEquals(1, rows[3].childCount) // an empty bucket is not a row + // The cleanups as commands/list gives them: each with its plan's scope and level. + fun command(id: String, group: String, plan: String, scope: String, level: Int, title: String) = + json("""{"id": "$id", "group": "$group", "title": "$title", "action": {"kind": "cache", "plan": "$plan", "scope": "$scope", "level": $level}}""") + val commands = listOf( + command("mcpp.clean", "project", "project", "project", 1, "Clean target"), + json("""{"id": "mcpp.build", "group": "project", "title": "Build", "action": {"kind": "job", "job": "build"}}"""), + command("mcpp.cleanStaleArtifacts", "cache", "stale", "project", 2, "Clean Stale Artifacts"), + command("mcpp.cleanProjectArtifacts", "cache", "project", "project", 1, "Clean Project Artifacts"), + command("mcpp.gcGlobalCache", "cache", "cacheGc", "shared", 2, "Collect the Shared Cache to a Budget"), + command("mcpp.verifyGlobalCache", "cache", "cacheVerify", "shared", 0, "Verify the Shared Cache")) + val sections = CacheModel.sections(inventory, null, commands, t) + assertEquals(listOf("Project cache", "Global build cache"), sections.map { it.row.text }) + // The project's section: its two cleanups, the one plan of mcpp.clean and mcpp.cleanProjectArtifacts once. + val project = sections[0].row + assertEquals("target/", project.detail) + assertEquals(listOf("Clean Stale Artifacts…", "Clean Project Artifacts…"), project.actions.map { it.label }) + assertEquals(listOf("stale", "project"), project.actions.map { it.plan }) + // The shared cache's: its total, its cleanups, and what the inventory says of it. + val shared = sections[1] + assertEquals("1.5 GiB in 2 entries", shared.row.detail) + assertEquals(listOf("Collect the Shared Cache to a Budget…", "Verify the Shared Cache"), shared.row.actions.map { it.label }) + assertEquals(listOf("/home/u/.mcpp", "By kind", "Largest", "By last use"), texts(shared)) + val ages = shared.getChildAt(3) as RowNode + assertEquals("0–7 days", (ages.getChildAt(0) as RowNode).row.text) + assertEquals(1, ages.childCount) // an empty bucket is not a row + // An inventory mcpp could not give is the shared cache's error; the project's section stays. + val failed = CacheModel.sections(null, "no mcpp", commands, t) + assertEquals(2, failed.size) + assertTrue((failed[1].getChildAt(0) as RowNode).row.error) + assertEquals("", failed[1].row.detail) + } + + @Test + fun aToolbarsTextIsReadWhenItIsShown() { + // The view is built before the session's strings arrive; the next time the toolbar is shown + // the action reads them (#13: an English tooltip beside Chinese rows). + val strings = mutableMapOf() + val action = io.github.mcppcommunity.mcppclion.ui.SessionAction({ strings["Refresh"] ?: "Refresh" }, com.intellij.icons.AllIcons.Actions.Refresh) {} + val event = com.intellij.testFramework.TestActionEvent.createTestEvent(action) + action.update(event) + assertEquals("Refresh", event.presentation.text) + strings["Refresh"] = "刷新" + action.update(event) + assertEquals("刷新", event.presentation.text) + } + + @Test + fun noClassOutsideUiJcefNamesJcef() { + // The JCEF plugin can be absent or disabled; a class of the core that names JCEF's fails to load + // there (#13). Only ui/jcef, which mcpp-jcef.xml registers, may. + val sources = java.io.File("src/main/kotlin") + assertTrue(sources.isDirectory) + val offending = sources.walk().filter { it.isFile && it.extension == "kt" && !it.path.replace('\\', '/').contains("/ui/jcef/") } + .filter { f -> f.readLines().any { it.startsWith("import com.intellij.ui.jcef") || it.startsWith("import org.cef") || it.contains("JBCef") } } + .map { it.name }.toList() + assertEquals(emptyList(), offending) + val optional = java.io.File("src/main/resources/META-INF/mcpp-jcef.xml").readText() + assertTrue(optional.contains("ui.jcef.JcefPageHost\$Factory")) } @Test diff --git a/mide-plugins/nvim/lua/mcpp/commands.lua b/mide-plugins/nvim/lua/mcpp/commands.lua index 99eef81..a8ab709 100644 --- a/mide-plugins/nvim/lua/mcpp/commands.lua +++ b/mide-plugins/nvim/lua/mcpp/commands.lua @@ -153,7 +153,7 @@ function panels.targets(row, _, root) end function panels.cache(row, _, root) - views.show(row.title, 'cache/inventory', { root = root }, views.cache_text) + views.show(row.title, 'cache/inventory', { root = root }, function(inv) return views.cache_text(inv, M.offered()) end) end function panels.graph(row, _, root) diff --git a/mide-plugins/nvim/lua/mcpp/session.lua b/mide-plugins/nvim/lua/mcpp/session.lua index 923473e..3039203 100644 --- a/mide-plugins/nvim/lua/mcpp/session.lua +++ b/mide-plugins/nvim/lua/mcpp/session.lua @@ -13,7 +13,7 @@ local uv = vim.uv or vim.loop local is_windows = vim.fn.has('win32') == 1 -- mcpp-nvim's version: mcpp-ide's, whose release carries it. -M.version = '1.5.0' +M.version = '1.6.0' -- Neovim's version, as its release names it. function M.nvim_version() diff --git a/mide-plugins/nvim/lua/mcpp/views.lua b/mide-plugins/nvim/lua/mcpp/views.lua index 0c0d9b7..79d89ad 100644 --- a/mide-plugins/nvim/lua/mcpp/views.lua +++ b/mide-plugins/nvim/lua/mcpp/views.lua @@ -189,31 +189,57 @@ function M.targets_text(r) return lines end -local function rows(into, list, label) +local function rows(into, list, label, indent) + indent = indent or ' ' for _, r in ipairs(list or {}) do - into[#into + 1] = string.format(' %-32s %10s %d', label(r), r.bytesText or '', r.entries or 0) + into[#into + 1] = string.format('%s%-30s %10s %d', indent, label(r), r.bytesText or '', r.entries or 0) end if not list or #list == 0 then - into[#into + 1] = ' ' .. t('none') + into[#into + 1] = indent .. t('none') end end --- cache/inventory: the total, by kind, the largest packages, by last use. -function M.cache_text(inv) +-- The cleanups of the command table for one scope (`project`, `shared`), as the subcommand that runs +-- each; an ellipsis marks one that asks first. Two commands of one plan are one, the cache group's, in +-- its place (as CLion's cache tab; design 2026-11-21). +local function cleanups(into, commands, scope) + local chosen = {} + for _, row in ipairs(commands or {}) do + local a = row.action or {} + if a.kind == 'cache' and a.scope == scope then + local kept = chosen[a.plan] + if not kept or (kept.group ~= 'cache' and row.group == 'cache') then chosen[a.plan] = row end + end + end + for _, row in ipairs(commands or {}) do + local a = row.action or {} + if a.kind == 'cache' and chosen[a.plan] == row then + into[#into + 1] = string.format(' :Mcpp %-28s %s%s', row.subcommand, row.title, (a.level or 0) > 0 and '…' or '') + end + end +end + +-- cache/inventory in the two sections of VS Code's page: the project's build with its cleanups, and +-- the shared cache -- its total, by kind, the largest packages, by last use -- with its own. +-- `commands` is the table Neovim offers (commands/list). +function M.cache_text(inv, commands) + local lines = { t('Project cache') .. ' · target/' } + cleanups(lines, commands, 'project') local where = (inv.root or '') ~= '' and (' · ' .. inv.root) or '' - local lines = { inv.totalText .. ' ' .. t('in {0} entries', inv.totalEntries) .. where, '' } - lines[#lines + 1] = t('By kind') - rows(lines, inv.byKind, function(r) return r.kind end) - vim.list_extend(lines, { '', t('Largest packages') }) - rows(lines, inv.topLabels, function(r) return r.label end) - vim.list_extend(lines, { '', t('By last use') }) + vim.list_extend(lines, { '', t('Global build cache') .. ' · ' .. inv.totalText .. ' ' .. t('in {0} entries', inv.totalEntries) .. where }) + cleanups(lines, commands, 'shared') + lines[#lines + 1] = ' ' .. t('By kind') + rows(lines, inv.byKind, function(r) return r.kind end, ' ') + lines[#lines + 1] = ' ' .. t('Largest packages') + rows(lines, inv.topLabels, function(r) return r.label end, ' ') + lines[#lines + 1] = ' ' .. t('By last use') rows(lines, inv.ageBuckets, function(b) return b.toDays == nil and t('older than {0} days', b.fromDays) or t('{0}–{1} days', b.fromDays, b.toDays) - end) + end, ' ') if inv.incomplete and #inv.incomplete > 0 then - vim.list_extend(lines, { '', t('Incomplete entries') }) + lines[#lines + 1] = ' ' .. t('Incomplete entries') for _, e in ipairs(inv.incomplete) do - lines[#lines + 1] = ' ' .. (e.label or e.key or '') + lines[#lines + 1] = ' ' .. (e.label or e.key or '') end end return lines diff --git a/mide-plugins/nvim/tests/smoke.lua b/mide-plugins/nvim/tests/smoke.lua index 71ce702..dc779d8 100644 --- a/mide-plugins/nvim/tests/smoke.lua +++ b/mide-plugins/nvim/tests/smoke.lua @@ -321,7 +321,16 @@ vim.cmd('Mcpp showTargets') local targets = float_text() check(':Mcpp showTargets lists the targets in a float', targets:find('linux', 1, true) ~= nil, targets:sub(1, 120)) vim.cmd('Mcpp showCachePanel') -check(':Mcpp showCachePanel shows the cache by kind', float_text():find('By kind', 1, true) ~= nil) +local cache = float_text() +check(':Mcpp showCachePanel shows the cache by kind', cache:find('By kind', 1, true) ~= nil) +-- The two sections of VS Code's page, each with its cleanups, one per plan. +check(':Mcpp showCachePanel shows the project cache and the global build cache', + cache:find('Project cache', 1, true) ~= nil and cache:find('Global build cache', 1, true) ~= nil, cache:sub(1, 200)) +local project_part = cache:sub(1, (cache:find('Global build cache', 1, true) or 1) - 1) +check('the project cleanups sit on the project section', + project_part:find(':Mcpp cleanStaleArtifacts', 1, true) ~= nil and project_part:find('cleanProjectArtifacts', 1, true) ~= nil + and project_part:find('gcGlobalCache', 1, true) == nil, project_part) +check('one action per plan, the cache group\'s', cache:find(':Mcpp clean ', 1, true) == nil, cache) vim.cmd('Mcpp project.showDependencyGraph') check(':Mcpp project.showDependencyGraph shows the packages', float_text() ~= '') diff --git a/mide-plugins/vscode/package-lock.json b/mide-plugins/vscode/package-lock.json index 9b018ab..583db59 100644 --- a/mide-plugins/vscode/package-lock.json +++ b/mide-plugins/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "mcpp-vscode", - "version": "1.5.0", + "version": "1.6.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "mcpp-vscode", - "version": "1.5.0", + "version": "1.6.0", "license": "Apache-2.0", "devDependencies": { "@mermaid-js/tiny": "12.2.0", diff --git a/mide-plugins/vscode/package.json b/mide-plugins/vscode/package.json index 87074d4..b9f4e31 100644 --- a/mide-plugins/vscode/package.json +++ b/mide-plugins/vscode/package.json @@ -2,7 +2,7 @@ "name": "mcpp-vscode", "displayName": "%displayName%", "description": "%description%", - "version": "1.5.0", + "version": "1.6.0", "publisher": "mcpp-community", "license": "Apache-2.0", "icon": "media/logo.png", @@ -1267,7 +1267,8 @@ ], "filenames": [ "mcpp.toml" - ] + ], + "configuration": "./syntaxes/mcpp-toml.language-configuration.json" } ], "configurationDefaults": { diff --git a/mide-plugins/vscode/syntaxes/mcpp-toml.language-configuration.json b/mide-plugins/vscode/syntaxes/mcpp-toml.language-configuration.json new file mode 100644 index 0000000..3dd7393 --- /dev/null +++ b/mide-plugins/vscode/syntaxes/mcpp-toml.language-configuration.json @@ -0,0 +1,12 @@ +{ + "comments": { "lineComment": "#" }, + "brackets": [["[", "]"], ["{", "}"]], + "autoClosingPairs": [ + { "open": "[", "close": "]" }, + { "open": "{", "close": "}" }, + { "open": "\"", "close": "\"", "notIn": ["string", "comment"] }, + { "open": "'", "close": "'", "notIn": ["string", "comment"] } + ], + "autoCloseBefore": ";:.,=}]) \n\t", + "surroundingPairs": [["[", "]"], ["{", "}"], ["\"", "\""], ["'", "'"]] +} diff --git a/mide-plugins/vscode/test/artifacts.test.ts b/mide-plugins/vscode/test/artifacts.test.ts index bdc6002..1c4d0c7 100644 --- a/mide-plugins/vscode/test/artifacts.test.ts +++ b/mide-plugins/vscode/test/artifacts.test.ts @@ -415,13 +415,14 @@ test("restoring other C++ services is offered only on a row that says it can be" assert.ok(!matches.test("mcppOtherCppFeatures")); }); -test("ships TOML highlighting for the exact mcpp.toml filename", () => { +test("ships TOML highlighting and its pairs for the exact mcpp.toml filename", () => { const manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as PackageManifest; const language = manifest.contributes?.languages?.find((item) => item.id === "mcpp-toml"); assert.deepEqual(language, { id: "mcpp-toml", aliases: ["mcpp TOML", "mcpp.toml"], filenames: ["mcpp.toml"], + configuration: "./syntaxes/mcpp-toml.language-configuration.json", }); const grammar = manifest.contributes?.grammars?.find((item) => item.language === "mcpp-toml"); diff --git a/mide-plugins/vscode/test/parity/manifest.test.ts b/mide-plugins/vscode/test/parity/manifest.test.ts index e949de4..6526e0d 100644 --- a/mide-plugins/vscode/test/parity/manifest.test.ts +++ b/mide-plugins/vscode/test/parity/manifest.test.ts @@ -39,8 +39,18 @@ test("every setting 0.9.0 contributed keeps its type, default, scope, order and assert.equal(now.contributes.configuration.title, old.contributes.configuration.title); }); -test("the views, languages, grammars, colours and the rest of the manifest are 0.9.0's", () => { - for (const key of ["viewsContainers", "views", "languages", "grammars", "colors", "problemMatchers", "viewsWelcome", "configurationDefaults"]) { +test("every language 0.9.0 contributed keeps each of its fields; a field may be added", () => { + // 1.6.0 gives mcpp-toml its language configuration (pairs, comments); nothing of 0.9.0's changes. + const byId = new Map>(now.contributes.languages.map((l: { id: string }) => [l.id, l])); + for (const language of old.contributes.languages) { + const current = byId.get(language.id); + assert.ok(current, language.id); + for (const [field, value] of Object.entries(language)) assert.equal(canon(current[field]), canon(value), `${language.id}.${field}`); + } +}); + +test("the views, grammars, colours and the rest of the manifest are 0.9.0's", () => { + for (const key of ["viewsContainers", "views", "grammars", "colors", "problemMatchers", "viewsWelcome", "configurationDefaults"]) { assert.equal(canon(now.contributes[key]), canon(old.contributes[key]), key); } for (const key of ["name", "publisher", "displayName", "description", "icon", "engines", "extensionDependencies", "capabilities", "main"]) { diff --git a/mide-plugins/vscode/test/toml/languageConfiguration.test.ts b/mide-plugins/vscode/test/toml/languageConfiguration.test.ts new file mode 100644 index 0000000..658e886 --- /dev/null +++ b/mide-plugins/vscode/test/toml/languageConfiguration.test.ts @@ -0,0 +1,38 @@ +/** + * mcpp.toml's language configuration (#15, #18): brackets and quotes close as they are typed, `#` + * comments a line, and a quote does not pair inside a string or a comment. The file is the one the + * manifest names and the package carries. + */ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import path from "node:path"; +import test from "node:test"; + +const root = process.cwd(); +const manifest = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")); +const language = manifest.contributes.languages.find((l: { id: string }) => l.id === "mcpp-toml"); +const file: string = language?.configuration ?? ""; +const configuration = JSON.parse(readFileSync(path.join(root, file), "utf8")); + +test("mcpp-toml names its language configuration, which the package carries", () => { + assert.ok(file.startsWith("./syntaxes/"), file); + const ignored = readFileSync(path.join(root, ".vscodeignore"), "utf8").split(/\r?\n/); + assert.ok(!ignored.some((line) => line.trim() === "syntaxes/**"), "syntaxes/ is packaged"); +}); + +test("brackets and quotes close, a quote not inside a string or a comment", () => { + const pairs = new Map( + configuration.autoClosingPairs.map((p: { open: string; close: string; notIn?: string[] }) => [p.open, p])); + assert.equal(pairs.get("[")?.close, "]"); + assert.equal(pairs.get("{")?.close, "}"); + for (const quote of ["\"", "'"]) { + assert.equal(pairs.get(quote)?.close, quote); + assert.deepEqual(pairs.get(quote)?.notIn, ["string", "comment"]); + } + assert.deepEqual(configuration.brackets, [["[", "]"], ["{", "}"]]); +}); + +test("a line comment is TOML's", () => { + assert.equal(configuration.comments.lineComment, "#"); + assert.equal(configuration.comments.blockComment, undefined); +}); diff --git a/protocol/protocol.schema.json b/protocol/protocol.schema.json index f04b69e..2ae2f27 100644 --- a/protocol/protocol.schema.json +++ b/protocol/protocol.schema.json @@ -561,7 +561,7 @@ "when": { "type": "string" }, "quickMenu": { "type": "boolean" }, "subcommand": { "type": "string", "description": "The name a command line types (`:Mcpp ` in Neovim): the row's own, else the id after `mcpp.`" }, - "action": { "type": "object", "required": ["kind"], "properties": { "kind": { "enum": ["job", "run", "debug", "cache", "panel", "cancel", "selectTarget", "installToolchain", "selectDefaultToolchain", "newProject", "quickMenu", "selfCheck", "rpc", "languageService", "forward", "editor", "problems", "report"] } } } + "action": { "type": "object", "required": ["kind"], "properties": { "kind": { "enum": ["job", "run", "debug", "cache", "panel", "cancel", "selectTarget", "installToolchain", "selectDefaultToolchain", "newProject", "quickMenu", "selfCheck", "rpc", "languageService", "forward", "editor", "problems", "report"] }, "scope": { "enum": ["project", "shared"], "description": "A cache action: what its plan acts on, the project's build (`target/`) or the shared cache (1.6.0 and later)" }, "level": { "type": "integer", "minimum": 0, "maximum": 3, "description": "A cache action: its plan's danger level, which decides what is asked before it runs (1.6.0 and later)" } } } } }, "launchParams": { "type": "object", "required": ["root"], "properties": { "root": { "type": "string" }, "target": { "type": "string" }, "profile": { "type": "string" }, "runner": { "type": "string", "description": "Explicit named runner; empty selects the default and disables automatic debuggee selection." }, "bin": { "type": "string" }, "test": { "type": "string" }, "cases": { "type": "array", "items": { "type": "string" } }, "args": { "type": "array", "items": { "type": "string" } } } }, diff --git a/spec/i18n/runtime.zh-cn.json b/spec/i18n/runtime.zh-cn.json index 51f5017..7a40fa3 100644 --- a/spec/i18n/runtime.zh-cn.json +++ b/spec/i18n/runtime.zh-cn.json @@ -833,5 +833,14 @@ "worker {0}": "工作线程 {0}", "Critical path": "关键路径", "Metrics appear when the project's mcpp states them (test-metrics, mcpp#917).": "项目的 mcpp 声明指标后才会显示(test-metrics,mcpp#917)。", - "This IDE runs without JCEF, which draws the test insights.": "此 IDE 未启用 JCEF,无法绘制测试洞察。" + "This IDE runs without JCEF, which draws the test insights.": "此 IDE 未启用 JCEF,无法绘制测试洞察。", + "default feature of {0}": "{0} 的默认 feature", + "feature of {0}": "{0} 的 feature", + "implies {0}": "隐含 {0}", + "A feature of {0}, as its mcpp.toml declares it.": "{0} 的 feature,按其 mcpp.toml 的声明。", + "On by default.": "默认开启。", + "Implies {0}.": "隐含 {0}。", + "{0} declares no feature {1}: it declares none": "{0} 未声明 feature {1}:它未声明任何 feature", + "{0} declares no feature {1}: it declares {2}": "{0} 未声明 feature {1}:它声明的是 {2}", + "mcpp states no features of an index package, which {0} asks for": "mcpp 未声明索引包的 feature({0} 提出了这一需求)" } diff --git a/src/documents.cppm b/src/documents.cppm index 78e1ff2..08aac25 100644 --- a/src/documents.cppm +++ b/src/documents.cppm @@ -191,6 +191,64 @@ Json markdown(std::string value) { return Json{{"kind", "markdown"}, {"value", s // LSP CompletionItemKind. constexpr int kFolder = 19, kSnippet = 15, kValue = 12, kModule = 9, kFunction = 3; +std::optional> read_lines(const std::filesystem::path& file) { + std::ifstream in(file, std::ios::binary); + if (!in) return std::nullopt; + return text::lines_of(std::string(std::istreambuf_iterator(in), {})); +} + +bool declares_workspace(const std::vector& lines) { + return std::ranges::any_of(lines, [](const std::string& l) { + const auto t = text::trim(l); + return t == "[workspace]" || t.starts_with("[workspace."); + }); +} + +// A dependency's features, from the manifest of the directory its `path` names, or for +// `workspace = true` the one the nearest enclosing workspace's `[workspace.dependencies]` names. One +// resolver serves one answer: each manifest, the workspace's included, is read once by it. +manifest::FeatureResolver feature_resolver(const Document& d) { + struct Memo { + std::map>> files; + const std::optional>& read(const std::filesystem::path& file) { + auto it = files.find(file); + if (it == files.end()) it = files.emplace(file, read_lines(file)).first; + return it->second; + } + std::optional workspace; + bool workspaceSought = false; + }; + return [dir = d.path.parent_path(), memo = std::make_shared()](const manifest::DependencyEdge& e) + -> std::optional> { + std::filesystem::path target; + if (e.path) { + target = dir / std::filesystem::path(*e.path); + } else if (e.workspace) { + if (!memo->workspaceSought) { + memo->workspaceSought = true; + auto at = dir; + for (int depth = 0; !at.empty() && depth < 64; ++depth, at = at.parent_path()) { + if (const auto& lines = memo->read(at / "mcpp.toml"); lines && declares_workspace(*lines)) { + memo->workspace = at; + break; + } + if (at == at.parent_path()) break; + } + } + if (!memo->workspace) return std::nullopt; + const auto& lines = memo->read(*memo->workspace / "mcpp.toml"); + const auto relative = lines ? manifest::workspace_dependency_path(*lines, e.name) : std::nullopt; + if (!relative) return std::nullopt; + target = *memo->workspace / std::filesystem::path(*relative); + } else { + return std::nullopt; + } + const auto& lines = memo->read((target / "mcpp.toml").lexically_normal()); + if (!lines) return std::nullopt; + return manifest::declared_features(*lines); + }; +} + } // namespace Options options_of(const Json& s, bool trusted, bool mcpplsServes, std::string_view locale) { @@ -239,6 +297,9 @@ Json diagnostics(const Document& d, const Options& o) { if (x.relatedKey) j["data"] = Json{{"relatedKey", *x.relatedKey}}; out.push_back(std::move(j)); } + for (const auto& x : manifest::feature_diagnostics(d.lines, feature_resolver(d), o.tomlSeverity.unknownKey, o.locale)) + out.push_back(Json{{"range", range(x.line - 1, x.start - 1, x.end - 1)}, {"severity", severity_number(x.severity)}, + {"code", x.code}, {"source", "mcpp"}, {"message", x.message}}); } if (d.kind == Kind::buildscript && o.bsDiagnostics && o.bsSeverity != "off") { for (const auto& x : buildscript::analyse(d.lines, o.bsSeverity, !o.mcpplsServes)) @@ -256,13 +317,15 @@ Json completion(const Document& d, int line, int character, const Options& o, co // The lines up to the cursor's, as the editor asks. const std::vector upTo(d.lines.begin(), d.lines.begin() + line + 1); auto suggestions = manifest::completions(upTo, line, character, o.locale); + // A dependency's features, from its own manifest (the whole document names its `path`). + if (suggestions.empty()) suggestions = manifest::feature_completions(d.lines, line, character, feature_resolver(d), o.locale); if (suggestions.empty() && o.indexCompletion && o.trusted) if (const auto at = manifest::dependency_version_context(upTo, line, character)) { if (catalogue) suggestions = manifest::version_suggestions(*at, manifest::catalogue_versions(*catalogue, at->name)); else needCatalogue = incomplete = true; } for (const auto& s : suggestions) { - Json item{{"label", s.label}, {"kind", s.kind == "section" ? kFolder : s.kind == "version" ? kValue : kSnippet}, + Json item{{"label", s.label}, {"kind", s.kind == "section" ? kFolder : s.kind == "version" || s.kind == "value" ? kValue : kSnippet}, {"detail", s.detail}, {"insertTextFormat", 2}, {"textEdit", Json{{"range", range(line, s.start, s.end)}, {"newText", s.insertSnippet.value_or(s.label)}}}}; if (s.documentation) item["documentation"] = markdown(*s.documentation); @@ -291,7 +354,8 @@ Json completion(const Document& d, int line, int character, const Options& o, co Json hover(const Document& d, int line, int character, const Options& o) { if (d.kind == Kind::manifest && o.tomlHover) { - const auto info = manifest::hover_at(d.lines, line, character); + auto info = manifest::feature_hover(d.lines, line, character, feature_resolver(d), o.locale); + if (!info) info = manifest::hover_at(d.lines, line, character); if (!info) return nullptr; auto value = std::format("**{}**\n\n{}", info->title, info->body); if (info->documentation) diff --git a/src/manifest.cppm b/src/manifest.cppm index f77aced..6ee7a47 100644 --- a/src/manifest.cppm +++ b/src/manifest.cppm @@ -28,7 +28,7 @@ using Json = nlohmann::json; struct Suggestion { std::string label; - std::string kind; // section | template | version + std::string kind; // section | template | version | value (a feature) std::string detail; std::optional documentation; std::optional insertSnippet; // a snippet (`${1:name}`); the label when none @@ -92,6 +92,43 @@ std::vector analyse(const std::vector& lines, const Dia // The outline: each table, and the keys under it (LSP DocumentSymbol). Json document_symbols(const std::vector& lines); +// ── a dependency's features (1.6.0) ──────────────────────────────────────── +// Read from the text of the dependency's own manifest, which a `path` names or the workspace's +// `[workspace.dependencies]` entry does: mcpp states no features of an index package (mcpp#992). + +struct Feature { + std::string name; + bool isDefault = false; + std::vector implies; +}; +// The features a manifest declares, as mcpp registers them: the keys of `[features]` (`default` +// among them) and `[features.]`, and the names of `[feature-deps.]` and, under a target +// selector, of `feature-deps`, `feature-requires-abi` and `feature-xlings`; nullopt when it declares +// none, which mcpp reads as a package that accepts any name. +std::optional> declared_features(const std::vector& lines); + +// A dependency as its edge names it: the key, and its `path` or `workspace = true`. +struct DependencyEdge { + std::string name; + std::optional path; + bool workspace = false; +}; +// The features of the manifest an edge leads to; nullopt when there is none to read or it declares +// none. The file system is the caller's. +using FeatureResolver = std::function>(const DependencyEdge&)>; +// The `path` a workspace's `[workspace.dependencies]` gives `name`. +std::optional workspace_dependency_path(const std::vector& lines, std::string_view name); + +// Inside the `features = [...]` of a dependency edge: the features its manifest declares and the edge +// does not name yet; a feature's hover; and a name the manifest does not declare (`unknownFeature`, +// at the severity of `unknownKey`). `lines` are the whole document's. +std::vector feature_completions(const std::vector& lines, int line, int character, + const FeatureResolver& resolve, std::string_view locale = "en"); +std::optional feature_hover(const std::vector& lines, int line, int character, + const FeatureResolver& resolve, std::string_view locale = "en"); +std::vector feature_diagnostics(const std::vector& lines, const FeatureResolver& resolve, + std::string_view severity, std::string_view locale = "en"); + // The snapshot's provenance. Json schema_source(); @@ -396,6 +433,62 @@ std::size_t first_non_space(std::string_view line) { return std::string_view::npos; } +// The keys inside an inline table: those of the table of its name (`app = { | }` under `[targets]` +// lists what `[targets.app]` does), less the ones the inline table has. A dependency's inline table is +// its specification, whose keys the schema does not list, and a table whose keys the user names has +// none to offer. A key is offered where one can begin: after the table's `{` or a `,`. +std::vector inline_table_keys(const Context& context, std::string_view lineText) { + if (context.table.kind != Resolution::Kind::known || kDependencyGroups.contains(context.table.group)) return {}; + if (!context.keyPrefix.empty()) return {}; + auto before = std::min(static_cast(std::max(0, context.replace.start)), lineText.size()); + while (before > 0 && (lineText[before - 1] == ' ' || lineText[before - 1] == '\t')) --before; + if (before > 0 && lineText[before - 1] != '{' && lineText[before - 1] != ',') return {}; + const auto* schemaSection = section_by_name(context.table.group); + if (!schemaSection || schemaSection->value("openKeys", false) || !keys_of(schemaSection)) return {}; + // The keys the inline table has after the cursor too, on its line, up to its `}`. + auto siblings = context.siblings; + { + auto bare_key_char = [](char c) { return std::isalnum(static_cast(c)) || c == '_' || c == '-'; }; + auto i = std::min(static_cast(std::max(0, context.replace.end)), lineText.size()); + int depth = 0; + bool expectKey = false; + char quote = 0; + for (; i < lineText.size(); ++i) { + const char c = lineText[i]; + if (quote) { + if (c == '\\' && quote == '"') ++i; + else if (c == quote) quote = 0; + continue; + } + if (c == '"' || c == '\'') { quote = c; continue; } + if (c == '#') break; + if (c == '{' || c == '[') { ++depth; continue; } + if (c == '}' || c == ']') { + if (depth == 0) break; + --depth; + continue; + } + if (depth == 0 && c == ',') { expectKey = true; continue; } + if (depth == 0 && expectKey && bare_key_char(c)) { + auto j = i; + while (j < lineText.size() && bare_key_char(lineText[j])) ++j; + siblings.emplace_back(lineText.substr(i, j - i)); + expectKey = false; + i = j - 1; + } + } + } + std::vector v; + for (const auto& key : *keys_of(schemaSection)) { + const auto name = str(key, "key"); + if (std::ranges::find(siblings, name) != siblings.end()) continue; + + v.push_back({name, "template", key_detail(key), key_documentation(key), name + " = " + key_placeholder(key), + context.replace.start, context.replace.end}); + } + return v; +} + } // namespace std::vector completions(const std::vector& lines, int line, int character, std::string_view locale) { @@ -421,7 +514,10 @@ std::vector completions(const std::vector& lines, int l if (context.kind == Context::Kind::key) { const auto& section = context.section; if (section.kind == Resolution::Kind::top) return out(header_suggestions(context.replace.start, context.replace.end, locale)); - if (section.kind != Resolution::Kind::known || !context.containerPath.empty()) return {}; + // Inside an inline table: the keys of the table of its name, as its own header would list them. + if (!context.containerPath.empty()) + return out(inline_table_keys(context, line >= 0 && line < static_cast(lines.size()) ? std::string_view(lines[line]) : std::string_view())); + if (section.kind != Resolution::Kind::known) return {}; if (kDependencyGroups.contains(section.group)) return out(template_suggestions(kDependencyTemplates, context.replace.start, context.replace.end, locale)); const auto* schemaSection = section_by_name(section.group); @@ -440,8 +536,11 @@ std::vector completions(const std::vector& lines, int l return out(template_suggestions(templates_of(section.group), context.replace.start, context.replace.end, locale)); } // A value: only an enum key's values; a free value is not guessed. - if (context.section.kind == Resolution::Kind::known) { - const auto* key = enum_key_of(section_by_name(context.section.group), context.keyPath); + if (context.section.kind == Resolution::Kind::known || context.table.kind == Resolution::Kind::known) { + const auto* key = context.section.kind == Resolution::Kind::known ? enum_key_of(section_by_name(context.section.group), context.keyPath) : nullptr; + // A key of an inline table or a dotted key: its own table's. + if (!key && context.keyPath.size() > 1 && context.table.kind == Resolution::Kind::known) + key = enum_key_of(section_by_name(context.table.group), {context.keyPath.back()}); if (key) { std::vector v; for (const auto& value : (*key)["values"]) { @@ -1138,7 +1237,9 @@ std::vector analyse(const std::vector& lines, const Dia continue; } const auto* info = key_info_of(section, key); - if (keys_of(section) && !section->value("openKeys", false) && !info) + // `app = { ... }` under [targets] (or [profile]) is the table [targets.app], which mcpp reads. + const bool namesEntry = headerName && (*headerName == "targets" || *headerName == "profile") && value.starts_with('{'); + if (keys_of(section) && !section->value("openKeys", false) && !info && !namesEntry) push("unknownKey", settings.unknownKey, std::format("unknown key {} in {}", key, str(*section, "header")), lineNumber, keyStart, keyEnd, key); if (info && info->value("legacy", false) == true && !(section && has_string(*section, "deprecatedBy"))) { @@ -1204,4 +1305,246 @@ Json schema_source() { return Json{{"version", str(schema(), "sourceVersion")}, {"commit", str(schema(), "sourceCommit")}}; } +// ── a dependency's features ── + +namespace { + +std::vector string_elements(const toml::Value& v) { + std::vector out; + if (v.kind != toml::ValueKind::array) return out; + for (const auto& e : v.elements) + if (e.kind == toml::ValueKind::string && e.text) out.push_back(*e.text); + return out; +} + +const toml::KeyValue* entry_of(const toml::Value& table, std::string_view key) { + for (const auto& e : table.entries) + if (e.keyPath.size() == 1 && e.keyPath[0].name == key) return &e; + return nullptr; +} + +// A dependency edge written as an inline table, with its `features` array when it has one. +struct EdgeAt { + DependencyEdge edge; + const toml::Value* features = nullptr; +}; + +std::vector edges_of(const toml::Document& doc) { + std::vector out; + std::vector sectionSegments; + for (const auto& node : doc.nodes) { + if (const auto* s = std::get_if(&node)) { + sectionSegments = s->isArray ? std::vector{} : segment_names(s->segments); + continue; + } + const auto& kv = std::get(node); + const auto group = group_of(sectionSegments); + if (!group || !kDependencyGroups.contains(*group) || *group == "workspace.dependencies") continue; + if (kv.keyPath.empty() || !kv.value || kv.value->kind != toml::ValueKind::inlineTable) continue; + EdgeAt at; + at.edge.name = join(segment_names(kv.keyPath)); + if (const auto* path = entry_of(*kv.value, "path"); path && path->value && path->value->kind == toml::ValueKind::string) + at.edge.path = path->value->text.value_or(""); + if (const auto* ws = entry_of(*kv.value, "workspace"); ws && ws->value && ws->value->kind == toml::ValueKind::boolean) + at.edge.workspace = ws->value->text == "true"; + if (const auto* f = entry_of(*kv.value, "features"); f && f->value && f->value->kind == toml::ValueKind::array) + at.features = &*f->value; + if (at.edge.path || at.edge.workspace) out.push_back(std::move(at)); + } + return out; +} + +std::optional> features_of(const FeatureResolver& resolve, const DependencyEdge& edge) { + if (!resolve || (edge.path && !relative_path(*edge.path))) return std::nullopt; + try { + return resolve(edge); + } catch (...) { + return std::nullopt; + } +} + +const Feature* find_feature(const std::vector& features, std::string_view name) { + const auto it = std::ranges::find(features, name, &Feature::name); + return it == features.end() ? nullptr : &*it; +} + +std::string quoted_list(const std::vector& names) { + std::string out; + for (const auto& n : names) out += (out.empty() ? "`" : ", `") + n + "`"; + return out; +} + +} // namespace + +std::optional> declared_features(const std::vector& lines) { + std::vector out; + std::vector defaults; + auto feature = [&](const std::string& name) -> Feature& { + auto it = std::ranges::find(out, name, &Feature::name); + if (it != out.end()) return *it; + out.push_back({name, false, {}}); + return out.back(); + }; + // Where the names of features begin in a table's segments: after `features` or `feature-deps`, + // or under a target selector after `feature-deps`, `feature-requires-abi` or `feature-xlings`; + // npos for another table. + auto names_at = [](const std::vector& segments) -> std::size_t { + if (!segments.empty() && (segments[0] == "features" || segments[0] == "feature-deps")) return 1; + if (segments.size() >= 3 && segments[0] == "target" && + (segments[2] == "feature-deps" || segments[2] == "feature-requires-abi" || segments[2] == "feature-xlings")) + return 3; + return std::string::npos; + }; + std::vector sectionSegments; + for (const auto& node : toml::parse(lines).nodes) { + if (const auto* s = std::get_if(&node)) { + sectionSegments = s->isArray ? std::vector{} : segment_names(s->segments); + const auto at = names_at(sectionSegments); + if (at != std::string::npos && sectionSegments.size() == at + 1) feature(sectionSegments[at]); + continue; + } + const auto& kv = std::get(node); + const auto at = names_at(sectionSegments); + if (kv.keyPath.empty() || at == std::string::npos) continue; + const auto key = kv.keyPath[0].name; + const bool features = sectionSegments[0] == "features"; + if (sectionSegments.size() == at + 1) { + if (features && key == "implies" && kv.keyPath.size() == 1 && kv.value) feature(sectionSegments[at]).implies = string_elements(*kv.value); + continue; + } + if (sectionSegments.size() != at || kv.keyPath.size() != 1) continue; + // `[feature-deps]` with `ssl = { ... }` names the feature ssl too. + auto& f = feature(key); + if (!features || !kv.value) continue; + if (key == "default") defaults = string_elements(*kv.value); + if (kv.value->kind == toml::ValueKind::array) f.implies = string_elements(*kv.value); + else if (kv.value->kind == toml::ValueKind::inlineTable) + if (const auto* implies = entry_of(*kv.value, "implies"); implies && implies->value) f.implies = string_elements(*implies->value); + } + if (out.empty()) return std::nullopt; + for (auto& f : out) f.isDefault = std::ranges::find(defaults, f.name) != defaults.end(); + return out; +} + +std::optional workspace_dependency_path(const std::vector& lines, std::string_view name) { + std::vector sectionSegments; + for (const auto& node : toml::parse(lines).nodes) { + if (const auto* s = std::get_if(&node)) { + sectionSegments = s->isArray ? std::vector{} : segment_names(s->segments); + continue; + } + const auto& kv = std::get(node); + if (group_of(sectionSegments) != std::optional("workspace.dependencies") || sectionSegments.size() != 2) continue; + if (join(segment_names(kv.keyPath)) != name || !kv.value || kv.value->kind != toml::ValueKind::inlineTable) continue; + const auto* path = entry_of(*kv.value, "path"); + if (path && path->value && path->value->kind == toml::ValueKind::string) return path->value->text.value_or(""); + return std::nullopt; + } + return std::nullopt; +} + +std::vector feature_completions(const std::vector& lines, int line, int character, + const FeatureResolver& resolve, std::string_view locale) { + auto t = [&](std::string_view key, const std::vector& args) { return i18n::translate(key, locale, args); }; + const int cursorLine = std::clamp(line, 0, std::max(0, static_cast(lines.size()) - 1)); + const int cursorCol = cursor_byte(lines, cursorLine, std::max(0, character)); + const auto doc = toml::parse(lines); + for (const auto& at : edges_of(doc)) { + // Inside the array's brackets: after `[`, before `]` when it is closed. + if (!at.features || !contains(at.features->range, cursorLine, cursorCol)) continue; + const auto& r = at.features->range; + if (cursorLine == r.startLine && cursorCol <= r.startCol) continue; + if (!at.features->open && cursorLine == r.endLine && cursorCol >= r.endCol) continue; + // An array left open runs to the end of the document: only its own line is inside it. + if (at.features->open && cursorLine != r.startLine) continue; + const toml::Value* element = nullptr; + for (const auto& e : at.features->elements) + if (contains(e.range, cursorLine, cursorCol) && !(cursorLine == e.range.startLine && cursorCol == e.range.startCol) && + !(cursorLine == e.range.endLine && cursorCol == e.range.endCol && !e.open)) + element = &e; + if (element && element->kind != toml::ValueKind::string) return {}; + const auto inside = element && element->contentRange && contains(*element->contentRange, cursorLine, cursorCol); + if (element && !inside) return {}; + const auto features = features_of(resolve, at.edge); + if (!features) return {}; + auto present = string_elements(*at.features); + int start = cursorCol, end = cursorCol; + if (inside) { + start = element->contentRange->startCol; + end = element->contentRange->endCol; + if (const auto it = std::ranges::find(present, element->text.value_or("")); it != present.end()) present.erase(it); + } + // A quoted name between two elements is separated from them by commas. + std::string before, after; + if (!inside) { + const std::string_view l = lines[cursorLine]; + auto b = std::min(cursorCol, l.size()); + while (b > 0 && (l[b - 1] == ' ' || l[b - 1] == '\t')) --b; + if (b > 0 && l[b - 1] != '[' && l[b - 1] != ',') before = ", "; + auto a = std::min(cursorCol, l.size()); + while (a < l.size() && (l[a] == ' ' || l[a] == '\t')) ++a; + if (a < l.size() && l[a] != ']' && l[a] != ',' && l[a] != '#') after = ", "; + } + std::vector v; + for (const auto& f : *features) { + if (std::ranges::find(present, f.name) != present.end()) continue; + auto detail = f.isDefault ? t("default feature of {0}", {at.edge.name}) : t("feature of {0}", {at.edge.name}); + if (!f.implies.empty()) detail += " · " + t("implies {0}", {join(f.implies, ", ")}); + v.push_back({f.name, "value", detail, std::nullopt, inside ? f.name : before + text::stringify(Json(f.name)) + after, + u16(lines, cursorLine, start), u16(lines, cursorLine, end)}); + } + return v; + } + return {}; +} + +std::optional feature_hover(const std::vector& lines, int line, int character, + const FeatureResolver& resolve, std::string_view locale) { + auto t = [&](std::string_view key, const std::vector& args) { return i18n::translate(key, locale, args); }; + if (line < 0 || line >= static_cast(lines.size())) return std::nullopt; + const int cursorCol = cursor_byte(lines, line, std::max(0, character)); + const auto doc = toml::parse(lines); + for (const auto& at : edges_of(doc)) { + if (!at.features) continue; + for (const auto& e : at.features->elements) { + if (e.kind != toml::ValueKind::string || !contains(e.range, line, cursorCol)) continue; + const auto features = features_of(resolve, at.edge); + if (!features) return std::nullopt; + const auto* f = find_feature(*features, e.text.value_or("")); + if (!f) return std::nullopt; + std::vector body{t("A feature of {0}, as its mcpp.toml declares it.", {"`" + at.edge.name + "`"})}; + if (f->isDefault) body.push_back(t("On by default.", {})); + if (!f->implies.empty()) body.push_back(t("Implies {0}.", {quoted_list(f->implies)})); + return HoverInfo{std::format("`{}`", f->name), paragraphs(body), std::nullopt}; + } + } + return std::nullopt; +} + +std::vector feature_diagnostics(const std::vector& lines, const FeatureResolver& resolve, + std::string_view severity, std::string_view locale) { + std::vector out; + if (severity == "off") return out; + auto t = [&](std::string_view key, const std::vector& args) { return i18n::translate(key, locale, args); }; + const auto doc = toml::parse(lines); + for (const auto& at : edges_of(doc)) { + if (!at.features) continue; + std::optional>> features; + for (const auto& e : at.features->elements) { + if (e.kind != toml::ValueKind::string || !e.text || e.text->empty() || e.open || e.range.startLine != e.range.endLine) continue; + if (!features) features = features_of(resolve, at.edge); + if (!*features) break; + if (find_feature(**features, *e.text)) continue; + std::vector names; + for (const auto& f : **features) names.push_back(f.name); + const auto message = names.empty() ? t("{0} declares no feature {1}: it declares none", {at.edge.name, *e.text}) + : t("{0} declares no feature {1}: it declares {2}", {at.edge.name, *e.text, join(names, ", ")}); + out.push_back({"mcpp.manifest.unknownFeature", message, std::string(severity), e.range.startLine + 1, + u16(lines, e.range.startLine, e.range.startCol) + 1, u16(lines, e.range.endLine, e.range.endCol) + 1, + std::nullopt}); + } + } + return out; +} + } // namespace mcppide::manifest diff --git a/src/server.cppm b/src/server.cppm index 6927c3b..a4e9fb6 100644 --- a/src/server.cppm +++ b/src/server.cppm @@ -35,13 +35,13 @@ export namespace mcppide::server { using Json = nlohmann::json; -inline constexpr std::string_view kVersion = "1.5.0"; +inline constexpr std::string_view kVersion = "1.6.0"; // THE SERIES (mcpp design 2026-11-07, D15): `X.Y` of `X.Y.Z`, shared by the backend and every editor // plugin; components of one series work together. A plugin refuses a backend of another series, // naming both versions. The backend is always `X.Y.0`: the VS Code and CLion packages carry it, so a // change of the backend is a change of every package, and it begins a series (1.3.0). `Z` is an // editor plugin's own patch. -inline constexpr std::string_view kSeries = "1.5"; +inline constexpr std::string_view kSeries = "1.6"; static_assert(kVersion.starts_with(kSeries) && kVersion.size() == kSeries.size() + 2 && kVersion.ends_with(".0")); inline constexpr int kProtocol = 2; @@ -223,7 +223,13 @@ private: // catalogue for minutes: kept until an index changes or the user asks. Json searchCache_; std::chrono::steady_clock::time_point searchAt_{}; + // A project's build database, with the time its manifest was written when it was asked: an entry + // is used only while the manifest is that one, so a graph asked right after the manifest changed + // does not wait for the watcher's next poll to be current. std::map buildDatabases_; + std::map> buildDatabaseStamps_; + std::optional cached_database(const std::filesystem::path& root); + void keep_database(const std::filesystem::path& root, Json envelope, std::optional stamp); struct Listing { std::vector records; bool current = true; // false once the project changed @@ -461,6 +467,7 @@ void Session::on_changed(const std::filesystem::path& root, std::string_view wha { std::lock_guard lock(mutex_); buildDatabases_.erase(root); + buildDatabaseStamps_.erase(root); if (auto it = listings_.find(root); it != listings_.end()) it->second.current = false; if (what != "result") frameworks_.erase(root); if (what != "result") probes_.erase(root); // a manifest may state another mcpp floor or pin @@ -616,11 +623,39 @@ std::expected Session::language_service_exec(const Json& p) { {"truncated", r->out_truncated || r->err_truncated}}; } -std::expected Session::build_database(const std::filesystem::path& root) { - { - std::lock_guard lock(mutex_); - if (auto it = buildDatabases_.find(root); it != buildDatabases_.end()) return it->second; +namespace { +std::optional manifest_stamp(const std::filesystem::path& root) { + std::error_code ec; + const auto t = std::filesystem::last_write_time(root / "mcpp.toml", ec); + if (ec) return std::nullopt; + return t; +} +} // namespace + +// The caller holds no lock. +std::optional Session::cached_database(const std::filesystem::path& root) { + const auto now = manifest_stamp(root); + std::lock_guard lock(mutex_); + const auto it = buildDatabases_.find(root); + if (it == buildDatabases_.end()) return std::nullopt; + if (const auto s = buildDatabaseStamps_.find(root); s == buildDatabaseStamps_.end() || s->second != now) { + buildDatabases_.erase(it); + buildDatabaseStamps_.erase(root); + return std::nullopt; } + return it->second; +} + +void Session::keep_database(const std::filesystem::path& root, Json envelope, std::optional stamp) { + std::lock_guard lock(mutex_); + buildDatabases_[root] = std::move(envelope); + buildDatabaseStamps_[root] = stamp; +} + +std::expected Session::build_database(const std::filesystem::path& root) { + if (auto cached = cached_database(root)) return *cached; + // The manifest's time before mcpp reads it: a change during the query leaves the entry stale. + const auto stamp = manifest_stamp(root); auto r = query(root, {"emit", "build-database", "--format", "json"}); if (!r) return std::unexpected(r.error()); if (r->exitCode != 0) { @@ -633,8 +668,7 @@ std::expected Session::build_database(const std::filesystem::p } if (r->envelope.is_null()) return std::unexpected(rpc::Error{rpc::REQUEST_FAILED, t("mcpp emit build-database printed no document")}); - std::lock_guard lock(mutex_); - buildDatabases_[root] = r->envelope; + keep_database(root, r->envelope, stamp); return r->envelope; } @@ -1144,6 +1178,7 @@ std::expected Session::project_new(const Json& p) { std::expected Session::manifest_check(const Json& p) { const auto root = root_of(p); if (root.empty()) return std::unexpected(invalid("manifest/check names its project's root")); + const auto stamp = manifest_stamp(root); auto r = query(root, {"emit", "build-database", "--format", "json"}); if (!r) return std::unexpected(r.error()); Json diags = Json::array(); @@ -1155,10 +1190,7 @@ std::expected Session::manifest_check(const Json& p) { else if (!std::filesystem::path(path).is_absolute()) d["path"] = (root / path).generic_string(); diags.push_back(std::move(d)); } - if (r->exitCode == 0) { - std::lock_guard lock(mutex_); - buildDatabases_[root] = r->envelope; - } + if (r->exitCode == 0) keep_database(root, r->envelope, stamp); return Json{{"root", root.generic_string()}, {"diagnostics", diags}}; } @@ -1359,6 +1391,12 @@ std::expected Session::capabilities_explain(const Json& p) { } features.push_back(std::move(f)); } + // An index package's features in mcpp.toml: mcpp states none in any release, and no capability is + // named yet (mcpp#992 asks for them); a `path` or workspace dependency's are read from its own + // manifest meanwhile (1.6.0). + features.push_back(Json{{"id", "manifest.packageFeatures"}, {"available", false}, + {"reason", Json{{"source", "mcpp"}, {"capability", ""}, {"need", "mcpp#992"}, {"have", probe.version}, + {"message", t("mcpp states no features of an index package, which {0} asks for", {"mcpp#992"})}}}}); return Json{{"root", root.generic_string()}, {"mcpp", probe_json(root, probe)}, {"features", features}}; } @@ -1450,6 +1488,13 @@ std::expected Session::commands(const Json& p) { row["action"]["command"] = (*it)[editor]; if (editor == "vscode" && it->contains("vscodeArguments")) row["action"]["arguments"] = (*it)["vscodeArguments"]; } + // A cleanup says what it acts on and how much it asks first, from its plan: a view places it + // with the project's build or with the shared cache, and invents no grouping of its own. + if (c.contains("action") && c["action"].value("kind", "") == "cache") + if (const auto plan = policy::plan(c["action"].value("plan", ""), {})) { + row["action"]["scope"] = plan->group == "clean" ? "project" : "shared"; + row["action"]["level"] = plan->level; + } const auto id = c.value("id", ""); row["title"] = spec::manifest_string(std::format("command.{}.title", id), locale); row["subcommand"] = spec::subcommand_of(c); @@ -1511,10 +1556,7 @@ std::expected Session::test_list(const Json& p) { std::vector Session::plan_packages(const std::filesystem::path& root, bool read) { Json db; - { - std::lock_guard lock(mutex_); - if (auto it = buildDatabases_.find(root); it != buildDatabases_.end()) db = it->second; - } + if (auto cached = cached_database(root)) db = *cached; if (db.is_null() && read) if (auto r = build_database(root)) db = *r; std::vector out; diff --git a/src/toml.cppm b/src/toml.cppm index 407da02..944cc01 100644 --- a/src/toml.cppm +++ b/src/toml.cppm @@ -109,6 +109,11 @@ struct Context { std::optional valueKind; bool insideString = false, stringOpen = false; ReplaceRange replace; + // key and value: the table the key belongs to when an inline table or a dotted key is read as + // the table of its name (`app = { kind = ... }` under `[targets]` is `[targets.app]`); for a key + // inside an inline table, the keys that table already has. + Resolution table; + std::vector siblings; }; // The document's structure. `lines` as text::lines_of gives them. @@ -266,6 +271,8 @@ private: int line_ = 0, col_ = 0; std::optional cursor_; std::optional> currentSection_; + // The keys of each inline table being scanned, innermost last. + std::vector> inlineKeys_; Pos pos() const { return {line_, col_}; } bool eof() const { return line_ >= static_cast(lines_.size()); } @@ -364,6 +371,13 @@ private: if (!currentSection_) return Resolution{}; return resolve_section(*currentSection_); } + // The table named by the current section's segments followed by `path`. + Resolution table_resolution(std::span path) const { + if (path.empty()) return section_resolution(); + auto segments = currentSection_.value_or(std::vector{}); + segments.insert(segments.end(), path.begin(), path.end()); + return resolve_section(segments); + } static std::vector names(const std::vector& segments) { std::vector out; @@ -382,6 +396,8 @@ private: c.section = section_resolution(); c.containerPath = std::move(containerPath); c.keyPrefix = std::move(keyPrefix); + c.table = table_resolution(c.containerPath); + if (!c.containerPath.empty() && !inlineKeys_.empty()) c.siblings = inlineKeys_.back(); c.replace = token ? token_replace(*token) : empty_replace(); capture(std::move(c)); } @@ -392,6 +408,7 @@ private: c.kind = Context::Kind::value; c.section = section_resolution(); c.keyPath = std::move(keyPath); + if (!c.keyPath.empty()) c.table = table_resolution(std::span(c.keyPath).first(c.keyPath.size() - 1)); c.valueKind = kind; c.insideString = insideString; c.stringOpen = stringOpen; @@ -634,6 +651,7 @@ private: Value node; node.kind = ValueKind::inlineTable; node.open = true; + inlineKeys_.emplace_back(); for (;;) { skip_trivia(); if (cursor_reached()) capture_key(keyPath, {}); @@ -649,9 +667,13 @@ private: continue; } const auto entryStart = pos(); - if (auto entry = scan_key_value(keyPath)) node.entries.push_back(std::move(*entry)); + if (auto entry = scan_key_value(keyPath)) { + if (!entry->keyPath.empty()) inlineKeys_.back().push_back(entry->keyPath.front().name); + node.entries.push_back(std::move(*entry)); + } if (same(pos(), entryStart)) advance(); } + inlineKeys_.pop_back(); node.range = range_from(start); return node; } diff --git a/tests/cts/rules.cpp b/tests/cts/rules.cpp index 63111a1..e7d4891 100644 --- a/tests/cts/rules.cpp +++ b/tests/cts/rules.cpp @@ -22,6 +22,17 @@ namespace { int failures = 0; +// The answers inside inline tables (and of nested keys) that 0.9 did not give: an inline table is read +// as the table of its name from 1.6.0 on (docs/rules.md). They are kept in golden/inline-tables.json, +// apart from 0.9's goldens, which give no answer at those positions; MCPP_IDE_WRITE_GOLDEN=1 writes +// the file again from this implementation, for review. +Json inlineSeen = Json::object(); + +bool inside_inline_table(const toml::Context& c) { + return (c.kind == toml::Context::Kind::key && !c.containerPath.empty()) || + (c.kind == toml::Context::Kind::value && c.keyPath.size() > 1); +} + void expect(const Json& got, const Json& want, const std::string& where) { if (got == want) return; if (++failures > 25) return; @@ -194,8 +205,13 @@ void check_manifest(const std::filesystem::path& file, const Json& golden) { list.push_back(j); } const auto& want = golden["completion"][at]; - expect(list, golden["lists"][want[0].get()], where + " completion"); - if (!items.empty()) expect(Json{items[0].start, items[0].end}, Json{want[1], want[2]}, where + " completion range"); + const auto& wantList = golden["lists"][want[0].get()]; + if (list != wantList && wantList.empty() && inside_inline_table(toml::context_at(upTo, l, c))) { + inlineSeen[where] = Json{{"items", list}, {"range", {items[0].start, items[0].end}}}; + } else { + expect(list, wantList, where + " completion"); + if (!items.empty()) expect(Json{items[0].start, items[0].end}, Json{want[1], want[2]}, where + " completion range"); + } const auto v = manifest::dependency_version_context(upTo, l, c); const Json wantV = golden.contains("versionContext") && golden["versionContext"].contains(at) ? golden["versionContext"][at] : Json(); expect(v ? Json{{"name", v->name}, {"insideString", v->insideString}, @@ -290,6 +306,16 @@ CTS rules{"rules", [] { else check_buildscript(f, golden); } check_catalogue(Json::parse(testsupport::read(root / "golden" / "catalogue.json"))); + const auto inlineGolden = root / "golden" / "inline-tables.json"; + if (std::getenv("MCPP_IDE_WRITE_GOLDEN")) { + std::ofstream(inlineGolden, std::ios::binary) << inlineSeen.dump(1) << "\n"; + } else { + const auto want = Json::parse(testsupport::read(inlineGolden)); + for (const auto& e : inlineSeen.items()) + expect(e.value(), want.contains(e.key()) ? want[e.key()] : Json(), e.key() + " completion (inline table)"); + for (const auto& e : want.items()) + if (!inlineSeen.contains(e.key())) expect(Json(), e.value(), e.key() + " completion (inline table)"); + } // The documents mcpp-vscode 0.9's parser tests read: their structure and every cursor's context. int k = 0; for (const auto& snippet : Json::parse(testsupport::read(root / "golden" / "snippets.json"))) @@ -308,6 +334,61 @@ CTS rules{"rules", [] { check(at && at->name == "zlib" && at->insideString); const auto suggestions = manifest::version_suggestions(*at, versions); check(suggestions.size() == 3 && suggestions[0].insertSnippet == "1.3.1" && suggestions[0].kind == "version"); + // An inline table is read as the table of its name (1.6.0): `app = { ... }` under [targets] has the + // keys of [targets.app], less those it has; its enum keys have their values; a dependency's inline + // table is its specification, which the schema does not list. + auto labels = [](std::string_view text, int line, int character) { + std::set out; + for (const auto& s : manifest::completions(text::lines_of(text), line, character)) out.insert(s.label); + return out; + }; + const auto targetKeys = labels("[targets]\napp = { kind = \"bin\", ", 1, 26); + check(targetKeys.contains("main") && targetKeys.contains("linkage") && !targetKeys.contains("kind")); + check(labels("[targets]\napp = { ", 1, 8).contains("kind")); + const auto kinds = labels("[targets]\napp = { kind = \"", 1, 15); + check(kinds.contains("bin") && kinds.contains("lib") && kinds.contains("entry")); + check(labels("[targets]\napp = { kind = ", 1, 14).contains("shared")); + check(labels("[features]\nsimd = { defines = [\"A\"], ", 1, 26).contains("sources")); + check(labels("[dependencies]\nfmt = { ", 1, 8).empty()); + check(labels("[dependencies]\nfmt = { version = \"1\", ", 1, 22).empty()); + check(labels("[targets]\napp = { kind = \"bin\" ", 1, 21).empty()); + check(labels("[package]\nmetadata = { ", 1, 13).empty()); + // A manifest's features in their three shapes; none when it declares no [features]. + const auto declared = manifest::declared_features(text::lines_of( + "[features]\ndefault = [\"a\"]\na = []\nb = [\"a\"]\nc = { defines = [\"C\"], implies = [\"b\"] }\n[features.d]\nimplies = [\"c\"]\n")); + // `default` is a key mcpp accepts as a name too. + check(declared && declared->size() == 5); + check((*declared)[0].name == "default" && (*declared)[0].implies == std::vector{"a"}); + check((*declared)[1].name == "a" && (*declared)[1].isDefault && !(*declared)[2].isDefault); + check((*declared)[2].implies == std::vector{"a"} && (*declared)[3].implies == std::vector{"b"}); + check((*declared)[4].name == "d" && (*declared)[4].implies == std::vector{"c"}); + check(!manifest::declared_features(text::lines_of("[package]\nname = \"x\"\n"))); + // An empty [features] declares none, which mcpp reads as accepting any name. + check(!manifest::declared_features(text::lines_of("[features]\n"))); + // The tables mcpp registers a feature by besides [features]. + const auto others = manifest::declared_features(text::lines_of( + "[feature-deps.ssl]\nopenssl = \"3\"\n[target.'cfg(os = \"linux\")'.feature-xlings.gtk]\nx = \"1\"\n[feature-deps]\nzip = { zlib = \"1\" }\n")); + check(others && others->size() == 3 && (*others)[0].name == "ssl" && (*others)[1].name == "gtk" && (*others)[2].name == "zip"); + check(manifest::workspace_dependency_path(text::lines_of("[workspace.dependencies]\ncore = { path = \"libs/core\" }\n"), "core") == "libs/core"); + // An index dependency has nothing to read: no resolver is asked. + bool asked = false; + const manifest::FeatureResolver none = [&](const manifest::DependencyEdge&) { asked = true; return std::nullopt; }; + check(manifest::feature_completions(text::lines_of("[dependencies]\nfmt = { version = \"1\", features = [] }\n"), 1, 37, none).empty() && !asked); + // Between elements a quoted name is separated by commas; an array left open is its own line only. + const manifest::FeatureResolver ab = [](const manifest::DependencyEdge&) { + return std::optional(std::vector{{"a", false, {}}, {"b", false, {}}}); + }; + const auto edge = text::lines_of("[dependencies]\nlib = { path = \"../lib\", features = [\"a\"] }\n"); + const auto first = manifest::feature_completions(edge, 1, 37, ab); + check(first.size() == 1 && first[0].insertSnippet == "\"b\", "); + const auto last = manifest::feature_completions(edge, 1, 40, ab); + check(last.size() == 1 && last[0].insertSnippet == ", \"b\""); + check(manifest::feature_completions(text::lines_of("[dependencies]\nlib = { path = \"../lib\", features = [\n[package]\nname = \"x\"\n"), 2, 0, ab).empty()); + // A key the inline table has after the cursor is not offered again; nor is an inline entry of + // [targets] an unknown key, since mcpp reads it as [targets.app]. + check(!labels("[targets]\napp = { kind = \"lib\", , main = \"x\" }", 1, 22).contains("main")); + check(labels("[targets]\napp = { kind = \"lib\", , main = \"x\" }", 1, 22).contains("linkage")); + for (const auto& d : manifest::analyse(text::lines_of("[targets]\napp = { kind = \"bin\" }\n"), {})) check(d.code != "mcpp.manifest.unknownKey"); // A suggestion's detail in the user's language. const auto zh = manifest::completions(text::lines_of("[dependencies]\n"), 1, 0, "zh-cn"); check(!zh.empty() && zh[0].detail != "SemVer version dependency"); diff --git a/tests/cts/rules/golden/inline-tables.json b/tests/cts/rules/golden/inline-tables.json new file mode 100644 index 0000000..f8c2a67 --- /dev/null +++ b/tests/cts/rules/golden/inline-tables.json @@ -0,0 +1,830 @@ +{ + "complete.toml 33:11": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 11, + 11 + ] + }, + "complete.toml 33:12": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 12 + ] + }, + "complete.toml 33:13": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:14": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:15": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:16": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:17": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:18": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + }, + "complete.toml 33:19": { + "items": [ + { + "detail": "array", + "documentation": "the features a consumer gets unless it opts out Since 0.0.47.", + "insertSnippet": "default = []", + "kind": "template", + "label": "default" + }, + { + "detail": "array", + "documentation": "[features.]: defines the active feature adds to the package's units Since 0.0.69.", + "insertSnippet": "defines = []", + "kind": "template", + "label": "defines" + }, + { + "detail": "array", + "documentation": "[features.]: the source extensions of a device language this rule package compiles Since 2026.9.7.1.", + "insertSnippet": "device_extensions = []", + "kind": "template", + "label": "device_extensions" + }, + { + "detail": "array", + "documentation": "[[features..flags]]: { glob, cflags, cxxflags, defines } tables for the feature's sources Since 0.0.101.", + "insertSnippet": "flags = []", + "kind": "template", + "label": "flags" + }, + { + "detail": "array", + "documentation": "[features.]: \"/\" entries activated with this feature Since 0.0.99.", + "insertSnippet": "forward = []", + "kind": "template", + "label": "forward" + }, + { + "detail": "array", + "documentation": "[features.]: the features this one activates Since 0.0.69.", + "insertSnippet": "implies = []", + "kind": "template", + "label": "implies" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature provides Since 0.0.69.", + "insertSnippet": "provides = []", + "kind": "template", + "label": "provides" + }, + { + "detail": "array", + "documentation": "[features.]: the capabilities the feature requires Since 0.0.69.", + "insertSnippet": "requires = []", + "kind": "template", + "label": "requires" + }, + { + "detail": "table", + "documentation": "[features.]: { threads, exceptions } the artefact's ABI switch must have when the feature is active Since 2026.9.12.2.", + "insertSnippet": "requires_abi = { }", + "kind": "template", + "label": "requires_abi" + }, + { + "detail": "string", + "documentation": "[features.]: the module of the build rule this feature contributes Since 2026.9.7.1.", + "insertSnippet": "rule_module = \"\"", + "kind": "template", + "label": "rule_module" + }, + { + "detail": "array", + "documentation": "[features.]: sources compiled only when the feature is active Since 0.0.95.", + "insertSnippet": "sources = []", + "kind": "template", + "label": "sources" + }, + { + "detail": "array", + "documentation": "[features.]: the host tools the feature makes available Since 2026.9.27.1.", + "insertSnippet": "tools = []", + "kind": "template", + "label": "tools" + } + ], + "range": [ + 12, + 19 + ] + } +} diff --git a/tests/e2e/probe.cpp b/tests/e2e/probe.cpp index 637b761..88c80d8 100644 --- a/tests/e2e/probe.cpp +++ b/tests/e2e/probe.cpp @@ -112,6 +112,10 @@ E2E probe{"probe", [] { explained = true; } check(explained); + // An index package's features wait for mcpp to state them, and the issue that asks is named. + check(std::ranges::any_of(why["features"], [](const Json& f) { + return f["id"] == "manifest.packageFeatures" && f["available"] == false && f["reason"]["need"] == "mcpp#992"; + })); // No run carries another project's pin: every run of mcpp removes XLINGS_PROJECT_DIR, which an // editor started from another project's terminal inherits (mcpp docs/50). The removal is the diff --git a/tests/e2e/protocol.cpp b/tests/e2e/protocol.cpp index 6ed9fa4..8a98e29 100644 --- a/tests/e2e/protocol.cpp +++ b/tests/e2e/protocol.cpp @@ -107,6 +107,59 @@ E2E protocol{"protocol", [] { check(hover["contents"]["value"].get().find("bmi_schedule") != std::string::npos); auto outline = result_of("textDocument/documentSymbol", Json{{"textDocument", {{"uri", tomlUri}}}}); check(outline.size() == 2 && outline[1]["name"] == "[build]" && outline[1]["children"].size() == 1); + // A dependency's features (1.6.0), read from its own manifest: a `path` one and a workspace one. + { + const auto ws = root / "features-ws"; + std::filesystem::create_directories(ws / "libs" / "core"); + std::filesystem::create_directories(ws / "libs" / "plain"); + std::filesystem::create_directories(ws / "app"); + std::ofstream(ws / "mcpp.toml", std::ios::binary) << "[workspace]\nmembers = [\"app\", \"libs/core\"]\n[workspace.dependencies]\ncore = { path = \"libs/core\" }\n"; + std::ofstream(ws / "libs" / "core" / "mcpp.toml", std::ios::binary) + << "[package]\nname = \"core\"\n[features]\ndefault = [\"fast\"]\nfast = []\ngui = [\"fast\"]\n[features.net]\nimplies = [\"fast\"]\n"; + std::ofstream(ws / "libs" / "plain" / "mcpp.toml", std::ios::binary) << "[package]\nname = \"plain\"\n"; + const auto appUri = testsupport::file_uri(ws / "app" / "mcpp.toml"); + const std::string app = "[package]\nname = \"app\"\n[dependencies]\ncore = { path = \"../libs/core\", features = [\"gui\", \"nope\"] }\n" + "plain = { path = \"../libs/plain\", features = [\"any\"] }\nmember = { workspace = true, features = [] }\n"; + wire.server.dispatch(Json{{"jsonrpc", "2.0"}, {"method", "textDocument/didOpen"}, + {"params", {{"textDocument", {{"uri", appUri}, {"languageId", "mcpp-toml"}, {"version", 1}, {"text", app}}}}}}.dump()); + // `nope` is reported; a dependency that declares no [features] accepts any name. + const auto diagnostics = wire.notifications("textDocument/publishDiagnostics").back(); + check(diagnostics["uri"] == appUri && diagnostics["diagnostics"].size() == 1); + check(diagnostics["diagnostics"][0]["code"] == "mcpp.manifest.unknownFeature"); + check(diagnostics["diagnostics"][0]["range"]["start"] == Json({{"line", 3}, {"character", 51}})); + check(diagnostics["diagnostics"][0]["message"].get().find("default, fast, gui, net") != std::string::npos); + auto atApp = [&](int line, int character) { + return Json{{"textDocument", {{"uri", appUri}}}, {"position", {{"line", line}, {"character", character}}}}; + }; + // Inside the array: the features the edge does not name yet, as quoted names. + std::map offered; + for (const auto& i : result_of("textDocument/completion", atApp(3, 44))["items"]) offered[i["label"].get()] = i; + check(offered.size() == 3 && offered.contains("default") && offered.contains("fast") && offered.contains("net") && !offered.contains("gui")); + check(offered["fast"]["textEdit"]["newText"] == "\"fast\", " && offered["fast"]["detail"].get().find("default") != std::string::npos); + // Inside a string: its content is replaced by the bare name. + std::set inString; + for (const auto& i : result_of("textDocument/completion", atApp(3, 46))["items"]) { + inString.insert(i["label"].get()); + check(i["textEdit"]["range"]["start"]["character"] == 45 && i["textEdit"]["newText"] == i["label"]); + } + // The name being edited is offered again; the others the edge names are not. + check(inString == std::set{"default", "fast", "gui", "net"}); + // A workspace dependency: the workspace's entry names its path. + wire.server.dispatch(Json{{"jsonrpc", "2.0"}, {"method", "textDocument/didChange"}, + {"params", {{"textDocument", {{"uri", appUri}, {"version", 2}}}, + {"contentChanges", Json::array({{{"text", "[dependencies]\ncore = { workspace = true, features = [] }\n"}}})}}}}.dump()); + std::set member; + for (const auto& i : result_of("textDocument/completion", atApp(1, 39))["items"]) member.insert(i["label"].get()); + check(member == std::set{"default", "fast", "gui", "net"}); + // A hover names the dependency, the default and what a feature implies. + wire.server.dispatch(Json{{"jsonrpc", "2.0"}, {"method", "textDocument/didChange"}, + {"params", {{"textDocument", {{"uri", appUri}, {"version", 3}}}, + {"contentChanges", Json::array({{{"text", "[dependencies]\ncore = { workspace = true, features = [\"gui\"] }\n"}}})}}}}.dump()); + const auto featureHover = result_of("textDocument/hover", atApp(1, 41))["contents"]["value"].get(); + check(featureHover.find("`gui`") != std::string::npos && featureHover.find("`core`") != std::string::npos && + featureHover.find("`fast`") != std::string::npos); + wire.server.dispatch(Json{{"jsonrpc", "2.0"}, {"method", "textDocument/didClose"}, {"params", {{"textDocument", {{"uri", appUri}}}}}}.dump()); + } // A change is the whole text; closing clears the document's diagnostics. wire.server.dispatch(Json{{"jsonrpc", "2.0"}, {"method", "textDocument/didChange"}, {"params", {{"textDocument", {{"uri", tomlUri}, {"version", 2}}}, {"contentChanges", Json::array({{{"text", "[package]\n"}}})}}}}.dump()); @@ -121,6 +174,16 @@ E2E protocol{"protocol", [] { check(!targets["rows"].empty()); auto cmds = result_of("mcpp-ide/commands/list", Json{{"editor", "jetbrains"}}); for (const auto& c : cmds["commands"]) check(c["action"]["kind"] != "forward"); + // A cleanup states its scope and its level, from its plan: a view places it by them. + std::map cleanups; + for (const auto& c : cmds["commands"]) + if (c["action"]["kind"] == "cache") cleanups[c["id"].get()] = c["action"]; + check(cleanups.size() == 7); + check(cleanups["mcpp.clean"]["scope"] == "project" && cleanups["mcpp.clean"]["level"] == 1); + check(cleanups["mcpp.cleanStaleArtifacts"]["scope"] == "project" && cleanups["mcpp.cleanStaleArtifacts"]["level"] == 2); + check(cleanups["mcpp.verifyGlobalCache"]["scope"] == "shared" && cleanups["mcpp.verifyGlobalCache"]["level"] == 0); + check(cleanups["mcpp.gcGlobalCache"]["scope"] == "shared" && cleanups["mcpp.cleanLegacyCache"]["level"] == 1); + check(conforms(cmds, protocol["methods"]["mcpp-ide/commands/list"]["result"], protocol, "commands/list (jetbrains)")); // Neovim's table: no forward to mcppls's commands (mcppls-nvim has its own), no panel it has no // text for, its own quickfix command, and each row's subcommand (`:Mcpp `). const Json nvimInit{{"clientInfo", {{"name", "Neovim"}}}, {"workspaceFolders", Json::array({Json{{"uri", testsupport::file_uri(root)}}})}, @@ -172,6 +235,13 @@ E2E protocol{"protocol", [] { std::filesystem::remove(badDatabase / ".mock-mcpp-fail"); check(!result_of("mcpp-ide/graph/packages", badRoot)["nodes"].empty()); check(!result_of("mcpp-ide/graph/modules", badRoot)["nodes"].empty()); + // A graph asked right after the manifest changed is the new manifest's, whatever the watcher has + // seen: the kept build database is used only while the manifest is the one it was read from. + std::ofstream(badDatabase / ".mock-mcpp-fail") << "manifest\n"; + std::ofstream(badDatabase / "mcpp.toml") << "[package]\nname = \"app\"\nversion = \"0.2.0\"\n"; + std::filesystem::last_write_time(badDatabase / "mcpp.toml", std::filesystem::last_write_time(badDatabase / "mcpp.toml") + std::chrono::seconds(2)); + check(wire.call("mcpp-ide/graph/modules", badRoot).contains("error")); + std::filesystem::remove(badDatabase / ".mock-mcpp-fail"); result_of("mcpp-ide/manifest/check", rooted); result_of("mcpp-ide/settings/registry", Json::object()); result_of("mcpp-ide/selfCheck", Json::object());