Skip to content

Add an embedded language server for open R documents - #905

Open
renkun-ken wants to merge 8 commits into
masterfrom
codex/webr-language-server
Open

renkun-ken wants to merge 8 commits into
masterfrom
codex/webr-language-server

Conversation

@renkun-ken

Copy link
Copy Markdown
Member

Summary

Add run_embedded() for editors hosting R in a dedicated worker. The host supplies complete JSON-RPC messages and forwards the returned replies. Buffer text and versioned edits stay in memory. The server reuses the package's parsers and language providers and can run without native R subprocesses or a mounted project tree.

This covers completion, hover, signatures, definitions, references, rename, Outline, folding and semantic tokens for open documents. Pull diagnostics report syntax errors and optionally spacing diagnostics with lintr. Full-document formatting is available when styler is installed.

Stacked on #903. The integration is tracked in vscode-R #2003.

Verification

  • Added tests for the lifecycle, workspace isolation, UTF-16 edits and positions, provider replies, incremental diagnostics, formatting, and release of closed documents.
  • Exercised the entry point under webR 0.6.1 / R 4.6.0 using the public Wasm language-server binary and the two R modules from this revision. Cross-buffer Go to Definition, editing, package completions, diagnostics and formatting ran in the worker.

@eitsupi eitsupi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by ChatGPT:

  1. "R/embedded.R": Go to Definition on string literals. "embedded_definition()" passes "rootPath = """ to "definition_reply()", which can call "with_wd(rootPath, ...)" when resolving a string literal as a file path. This results in a "setwd("")" error. Please disable filesystem-based definition lookup in embedded mode rather than passing an invalid working directory.

  2. Partial rename across open documents. Renaming a global binding can silently leave references in closed files unchanged, potentially breaking the project. Given the existing safeguards against incomplete rename operations, please consider restricting such renames or explicitly notifying users of their limited scope. Implementing closed-file indexing is not required for this PR.

  3. Missing "prepareRename" capability. The embedded server implements "textDocument/prepareRename" but advertises only "renameProvider = TRUE". Please advertise "prepareProvider = TRUE" when the client supports it, consistent with the existing capability negotiation in "R/capabilities.R".

  4. Workspace folder changes. Workspace folders are captured during initialization but subsequent additions and removals are not handled. This can leave document isolation inconsistent with the current workspace configuration. Please either handle these changes or document that the host must restart the embedded server when workspace folders change.

  5. Configuration support. Most existing language server settings are not synchronized in embedded mode, and formatting is hardcoded to styler. Please document which settings are supported and which are ignored. Full configuration parity is not required for this PR.

@renkun-ken

Copy link
Copy Markdown
Member Author

Thanks for the review. The five findings are addressed in 9eb1f28.

  1. Go to Definition on strings. The embedded resolver disables filesystem lookup with a null root. Both string-literal paths, including the fallback in the shared resolver, skip filesystem access. Open-buffer symbol definitions still resolve.
  2. Rename scope. A function-body local can be renamed directly. For project-level bindings and potentially externally named function arguments, a supporting client receives versioned edits annotated Rename in open documents only and must confirm them. Clients without that confirmation capability receive a request error. A standalone workspace containing only untitled scratch buffers can still rename across those buffers.
  3. Prepare Rename. Initialization advertises prepareProvider when the client declares prepareSupport. Prepare and Rename enforce the same scope rules.
  4. Workspace folders. The server negotiates folder-change notifications, then regroups open documents under the most specific current folder. It preserves unsaved text and document versions and rebuilds affected parse state. The tests add and remove a nested root and verify cross-file navigation on either side of the change.
  5. Configuration. The README and ?run_embedded describe diagnostics, the in-process lintr spacing rule, syntax diagnostics under other backend selections, and full-document formatting with styler. They also identify the native formatter, external tools, indexing, and other settings that the embedded entry point does not synchronize.

R CMD check --no-manual completed with Status: OK on both this PR and the session-package follow-up in #907. A webR 0.6.1 worker exercised literal lookup, negotiated capabilities, annotated and local renames, and unsaved documents moving between folder scopes.

@renkun-ken
renkun-ken added this pull request to stack #910 November 30, 2026 02:07
@renkun-ken
renkun-ken force-pushed the codex/webr-language-server branch from 9eb1f28 to 71e71b3 Compare November 30, 2026 05:53

@eitsupi eitsupi left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by ChatGPT:

The previous review findings have been addressed. The embedded language server is within the scope of the languageserver package, and there are precedents for this approach, notably Postgres Language Server and Tombi, which provide APIs for embedding language servers in browser environments.

Keeping run_embedded() in languageserver rather than implementing it in vscode-R or a separate R package is appropriate, given its reliance on internal language providers and data structures. The API itself is independent of webR and VS Code, making it potentially useful to other hosts.

One longer-term concern is the duplication of LSP dispatch, lifecycle management, capability negotiation, document synchronization, and configuration handling between the native and embedded servers. I suggest gradually extracting a shared, transport-independent language server core, with differences in execution environments, task scheduling, and filesystem access handled separately. This would reduce the risk of behavioral divergence and the maintenance burden when introducing new language features.

Also, since run_embedded() constructs and returns a stateful dispatcher rather than running a message loop, a name such as create_embedded_server() might describe its semantics more accurately.

Neither suggestion needs to block this PR. The current implementation is a reasonable starting point, and a larger refactoring can be considered separately.

@renkun-ken renkun-ken left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would fix the two rename cases before merging. A rename in one notebook can propose edits in a different workspace folder, and a rename in an untitled buffer can target the generated read-only source of stats::lm. The inline comments include reproductions for both, plus the completion, diagnostics, formatting, and document-lifetime issues.

All 81 assertions in test-embedded.R passed on native R 4.6.1, and all 16 GitHub checks passed on 71e71b3. I also exercised the dispatcher in webR 0.6.1 / R 4.6.0 using the PR’s R modules over the published Wasm package. I verified parse-snapshot retention separately with a native R finalizer.

Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
Comment thread R/embedded.R Resolved
@renkun-ken

renkun-ken commented Nov 30, 2026 •

Copy link
Copy Markdown
Member Author

Addressed all eight findings from the review in 8afd676.

  • Notebook and package-source scope. A notebook cell uses the scheme, authority and path of its owning notebook to select a workspace folder. Definitions, references and rename edits keep the original cell URI. Generated package sources have their own read-only scope. Opening the definition of stats::lm still allows package navigation and no longer adds edits to that document when renaming model.matrix in a scratch buffer.
  • R Markdown and Quarto. Each executable R chunk is parsed and linted independently, and chunk boundaries contribute to the diagnostic result ID. Syntax diagnostics use R’s structured coordinates when available and map them to document UTF-16 positions. Formatting skips a chunk styler cannot parse and still returns valid text edits for its siblings.
  • Completion and local rename. Relative paths in source() and sys.source() complete from open editor URIs, including directories implied by those URIs. The worker’s working directory is never enumerated for these suggestions. Rename and Prepare Rename inside a glue() interpolation follow its resolved lexical binding. Project bindings and externally callable formals retain the existing confirmation requirement.
  • Document lifetime. Closing a document invalidates cached namespace snapshots immediately. Closing the last document in a scope evicts its workspace. A finalizer regression test checks both lifetimes without an intervening language request.

I replayed the review cases on native R 4.6.1 and on webR 0.6.1 with R 4.6.0, using the published Wasm package and the pinned R modules. In VS Code for the Web, two real Jupyter notebooks in different folders verified both directions of Go to Definition and the exact reference and rename targets. The session-aware follow-up #907 and the vscode-R integration now consume the fixes.

The full native package check on this revision passed 24,499 assertions, with two optional datawizard tests skipped. The all-platform GitHub R package checks and all four coverage shards also passed.

@renkun-ken
renkun-ken requested a review from eitsupi November 30, 2026 17:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants