Skip to content

Experimental ReScript Language Server in OCaml - #8425

Open
aspeddro wants to merge 12 commits into
rescript-lang:masterfrom
aspeddro:lsp
Open

aspeddro wants to merge 12 commits into
rescript-lang:masterfrom
aspeddro:lsp

Conversation

@aspeddro

@aspeddro aspeddro commented May 14, 2026 •

Copy link
Copy Markdown
Contributor

This branch introduces a ReScript LSP server built on top of the existing
analysis library. It runs in-process through rescript lsp --stdio, using the
new rescript CLI written in OCaml (rewatch-ocaml). There is no separate
rescript-language-server executable. It's a separate, OCaml-side exploration
alongside the Rust/rewatch-based experiment in #8243, the two share the same
goal (a LSP server for ReScript) but approach it from different ends of the
toolchain.

Why rewriting the server in OCaml is a good fit

The editor features are already implemented in the OCaml analysis library.
Hover, completion, references, rename, document symbols, code actions, and
diagnostics all depend on compiler data structures such as .cmt / .cmti,
typed trees, locations, package metadata, and compiler diagnostics. Running the
LSP server in OCaml lets the server call those APIs directly instead of shelling
out to rescript-editor-analysis.exe or passing JSON through stdin. That
removes a large amount of process orchestration and serialization glue, and
keeps the LSP closer to the compiler types it needs to understand. This also
makes the server easier to evolve with the compiler. When typedtree, diagnostic
formats, package discovery, or .cmt handling changes, the LSP can be updated
in the same language and build system as the analysis code. That reduces version
skew and makes bugs easier to reproduce with Dune/expect tests.

Why ship the language server with the compiler

The language server is tightly coupled to the compiler version used by a
project. It reads .cmt and .cmti files containing marshalled compiler
internals such as Typedtree, Types, and Env. These files are not a stable,
schema-aware protocol: changing one of those OCaml types can make an analysis
binary incompatible with artifacts produced by another compiler revision.

This is not only a theoretical compatibility concern. In
#8475, adding typedtree
constructors for for...of without changing the CMT magic number allowed a
newer analysis binary to read incompatible ReScript 12 artifacts and
segmentation fault. The same class of failure appeared after record-rest changes
altered compiler data stored in CMT files. Bumping the CMT magic number makes
these mismatches rejectable, but the project must still be rebuilt with the
matching compiler.

Shipping the server in the same platform package as the compiler, and exposing
it through rescript lsp --stdio, gives clients one project-local entrypoint.
The selected ReScript dependency then supplies bsc, the analysis code, and the
language server from the same release. This has several practical benefits:

  • Editors do not need to install or select a separate language-server version.
  • Projects pinned to different ReScript versions get the corresponding server.
  • Compiler, analysis, and LSP changes can be released and upgraded atomically.
  • The OCaml rescript executable links the server library directly, so no
    separate language-server executable needs to be located or launched.

Bundling does not make stale artifacts safe. Compiler changes that alter
marshalled CMT data must still bump the magic number, and the server should turn
version mismatches into an actionable request to rebuild. A separately versioned
server becomes practical only if analysis moves to a stable, explicitly
versioned artifact format or maintains decoders for multiple compiler-internal
formats. Until then, promising one server binary that supports multiple compiler
versions would hide a compatibility boundary that already exists.

What's here

  • The server library lives in lsp/src, with its own opam package
    (rescript-language-server.opam). It uses lsp (>= 1.22.0), eio,
    ppx_deriving_yojson, ppx_expect and the in-tree analysis library.
  • The entrypoint is rewatch-ocaml/rescript_ocaml.ml. The OCaml rescript
    executable links the server library and uses Eio_main.run to supply its
    filesystem, stdin and stdout.
  • Start the server with rescript lsp --stdio. The --stdio flag is required:
    rescript lsp without it fails and displays usage help. The LSP subcommand
    does not accept --quiet or --verbose.
  • End-to-end snapshot tests in tests/lsp_tests exercise the server through the
    same OCaml CLI entrypoint.

Status / what's not here yet

The main objective is to first maintain feature parity with the current server
(server.ts) as much as possible. Below is a list of some requests and
notifications. Some are out of scope because they don't make sense.

  • initialize - client request
  • initialized - client notification
  • shutdown - client request
  • exit - client notification
  • textDocument/didOpen - client notification
  • textDocument/didChange - client notification
    • Incremental change
  • textDocument/didClose - client notification
  • textDocument/didSave - client notification - It will not be
    implemented for now.
  • textDocument/hover - client request
  • textDocument/publishDiagnostics - server notification
    • More work was needed for some kinds of errors. How should circular
      dependency errors be published?
      • Circular dependency diagnostics are special-cased because the compiler log
        does not point at a precise source range. When the document is open, we
        expand the diagnostic range to cover the whole document so the editor can
        display a file-level diagnostic. If the document is not open, we keep the
        range parsed from the compiler log, i.e.,
        {start: {line: 0, character: 0}, end: {line: 0, character: 6}}
        • The shortest possible code has at least 7 characters: let a=1.
          Protocol positions are zero-based, so the position is length - 1.
    • Use Analysis for syntax errors and ignore them in the compiler log
      parser.
      • This lets the server publish syntax errors on TextDocumentDidChange and
        provide instant feedback.
    • Compiler-log diagnostics from .compiler.log - server feature
      • Add more test cases; see compiler_log.ml. See tests/build_tests
        for more examples.
    • Monorepo diagnostics via .sourcedirs.json - server feature
      • Requires ReScript v12.1.0. In this version, .sourcedirs.json is always
        generated with build_root field for each subpackage.
    • Add the warning number to the diagnostic message.
  • workspace/didChangeWatchedFiles - client notification
    • The server uses this notification to detect changes to generated
      .compiler.log files, which usually means a ReScript build has finished.
      When a watched log changes, the server re-reads every known compiler log and
      republishes diagnostics so stale errors are cleared and monorepo diagnostics
      stay in sync.
    • Use GlobPattern with baseUri (workspace root)?
    • Should we watch all rescript.json files in the workspace root?
      • Some features require data defined in rescript.json. For example,
        suffix and package-specs are needed to create the code action
        Open compiled JS file. Changes in dependencies impact various
        functionalities because they modify the state in
        Analysis.Shared_types.state.
      • Users can restart the server after changing the configuration.
  • client/registerCapability - server request
    • We use this because workspace/didChangeWatchedFiles is commonly registered
      dynamically. The server does not know all file-watch patterns during the
      static initialize response. In this LSP, the watcher list depends on
      project state, especially .sourcedirs.json, which tells us where each
      ReScript build root lives. In monorepos, that means the server needs to
      register watchers for compiler logs after initialization, once it has
      workspace context. That means watching generated .compiler.log files. When
      the client sees one change, it sends workspace/didChangeWatchedFiles, and
      the server refreshes diagnostics.
  • textDocument/diagnostic - client request
  • textDocument/completion - client request
  • completionItem/resolve - client request
  • textDocument/signatureHelp - client request
  • textDocument/definition - client request
  • textDocument/declaration - client request - It will not be implemented
    for now.
  • textDocument/typeDefinition - client request
  • textDocument/implementation - client request - It will not be
    implemented for now.
  • textDocument/references - client request
  • textDocument/documentHighlight - client request - It will not be
    implemented for now.
  • textDocument/documentSymbol - client request
    • Zed needs the "document_symbols": "on" configuration. When enabled,
      tree-sitter is not used for document symbols.
  • workspace/symbol - client request - It will not be implemented for
    now.
  • textDocument/codeAction - client request
    • Code actions from analysis
    • Code actions from diagnostics (refactor, quick fixes, etc)
    • Open compiled js file (Trigger workspace execute command
      rescript/openCompiled)
      • Available if the client supports window/showDocument.
    • Create interface file (Trigger workspace execute command
      rescript/createInterface)
      • Available if the interface does not exist.
    • Switch to implementation/interface (Trigger workspace execute command
      rescript/switchImplementationInterface)
      • Available if the client supports the window/showDocument request.
  • codeAction/resolve - client request - It will not be implemented for
    now.
  • textDocument/codeLens - client request
  • workspace/codeLens/refresh - server request
  • codeLens/resolve - client request - It will not be implemented for
    now.
  • textDocument/inlayHint - client request
  • inlayHint/resolve - client request - It will not be implemented for
    now.
  • textDocument/semanticTokens/full - client request
  • textDocument/semanticTokens/full/delta - client request - It will not
    be implemented for now.
  • textDocument/semanticTokens/range - client request - It will not be
    implemented for now.
  • textDocument/rename - client request
  • textDocument/prepareRename - client request
  • textDocument/formatting - client request
  • textDocument/rangeFormatting - client request - It will not be
    implemented for now.
  • textDocument/onTypeFormatting - client request - It will not be
    implemented for now.
  • textDocument/foldingRange - client request - It will not be
    implemented for now.
  • textDocument/selectionRange - client request - It will not be
    implemented for now.
  • textDocument/documentLink - client request - It will not be
    implemented for now.
  • documentLink/resolve - client request - It will not be implemented for
    now.
  • textDocument/documentColor - client request - It will not be
    implemented for now.
  • textDocument/linkedEditingRange - client request - It will not be
    implemented for now.
  • workspace/didChangeConfiguration - client notification
  • workspace/configuration - server request
  • workspace/executeCommand - client request
    • rescript/dumpServerState
      • Dump the State.t (diagnostics, document store, status, configuration,
        analysis state (Analysis.Shared_types.state) and compiler config).
      • Write a temporary .json file and open it using window/showDocument.
        Requires client support for that request; the command returns no content.
    • rescript/openCompiled: Triggered by a code action
      • Only works if the client supports window/showDocument.
    • rescript/createInterface: Triggered by a code action
      • The server creates the interface if it does not exist and opens the
        interface file if the client supports the window/showDocument request.
      • If the interface file already exists, the server sends an error.
    • rescript/switchImplementationInterface: Triggered by a code action
      • Only available if the client supports the window/showDocument request.
    • rescript/dumpCmt: Dump cmt file content
      • Write a temporary .txt file and open it using window/showDocument.
        Requires client support for that request; the command returns no content.
    • rescript/dumpParseTree It will not be implemented for now.
      • Dump parsed tree
    • rescript/dumpTypedTree It will not be implemented for now.
      • Dump typed tree
    • Flow to execute a command:
  • Custom requests
    • textDocument/openCompiled - client request
    • textDocument/createInterface - client request
    • textDocument/switchImplementationInterface: Currently it's done on the
      client side, but it could be a command triggered by a code action.
      • Move to code action feature
    • rescript/startBuild - client request - How the build integration
      will be done. See last point
      . It will not be implemented for now
      • Some questions
        • Create a setting to automatically start the build watcher during
          initialization and drop this custom request?
        • When should the build watcher be stopped? On shutdown/exit?
        • Create work-done progress?
        • Add a custom request to kill the watcher rescript/stopBuild?
  • Custom notifications
  • Channels to support
    • The current server (server.ts) supports stdio and node-ipc. The VSCode
      client uses node-ipc. This implementation supports only stdio.
    • stdio
    • socket - It will not be implemented for now
  • Incremental compilation - server feature - It will
    not be implemented for now.
  • Build integration managed by the LSP server - server feature - It will
    not be implemented for now.
    • Build integration is still external: diagnostics come from compiler logs
      produced by an existing rescript build, rather than the LSP starting or
      managing builds itself.
  • First-class compiler support on the server. It will not be implemented
    for now. Idea to explore.

Tests

tests/lsp_tests/ contains OCaml ppx_expect end-to-end tests, with a named
let%expect_test for each scenario and separate modules for each feature.
Representative cases are adapted from tests/analysis_tests; the original
analysis suite remains in place. Source snippets no longer contain cursor
markers: requests use explicit, zero-based LSP positions.

The shared client in test.ml starts
rewatch-ocaml/rescript_ocaml.exe lsp --stdio through Unix.open_process_args,
avoiding Eio.Stdenv.process_mgr in the test harness so it can run on Windows,
Linux and macOS. Dune declares the CLI executable as a test dependency. The
harness supplies RESCRIPT_RUNTIME because it bypasses the npm launcher.

Tests create their source files and rescript.json from OCaml.
Test.setup_project writes the project and optionally builds it;
Test.with_project manages a temporary workspace and cleanup. Tests can add
multiple documents, edit unsaved buffers, rebuild, change settings and vary
client capabilities. Snapshots normalize temporary workspace paths while
preserving ranges and response ordering.

Coverage includes hover and JSX hover, completion and JSX completion, completion
resolution, definitions, type definitions, references, prepare rename, rename,
document symbols, semantic tokens, signature help, interface creation, code
actions, inlay hints, syntax diagnostics and code lenses. Diagnostic regression
tests cover build-log updates, stale warnings, duplicate publications, flicker
and document closure. Execute-command tests check the temporary state/CMT dump
files and window/showDocument capability handling. These tests do not imply
complete coverage or feature parity with the existing server.

Build the toolchain and runtime and run the LSP suite with:

opam exec -- make test-lsp

After the toolchain and runtime are built, run just the integration suite with
opam exec -- dune runtest tests/lsp_tests. Run opam exec -- dune runtest to
also cover inline tests in the server library, including .sourcedirs.json
build-root extraction and .compiler.log parsing. See
the snapshot test guide for helpers and commands
to review and promote snapshots.

Breaking Changes

Server settings

Proposed interface.

  • Currently (server.ts), supportMarkdownLinks is not a setting. It's a great
    feature, but some clients don't have good support; Neovim are a example.
    Therefore, I'm promoting it to a setting so users can enable or disable it.
/**
 * Server settings.
 * These configurations are requested by the server using `workspace/configuration`.
 */
interface Settings {
  hover?: {
    /**
     * Enable markdown links in hover responses
     * @default false
     */
    supportMarkdownLinks?: boolean;
  };
  /**
   * Enable code lenses for function definitions, showing the full type above each definition
   * @default false
   */
  codeLens?: boolean;
  /**
   * Place annotations inline with text to display type hints
   */
  inlayHints?: {
    /**
     * Enable inlay hints
     * @default false
     */
    enable?: boolean;
    /**
     * Maximum number of characters for inlay hints. Set to null to have an unlimited length.
     * Inlay hints that exceed the maximum length will not be shown
     * @default 25
     */
    maxLength?: number | null;
  };
}

Release and transition plan

How should the server be published? How should developers use the server?

Other related topics

Refactor analysis for use on the server side

  • Parsing from source (not just files) / decouple I/O from core logic
    #8426
    #8466
    #8478
  • Use the yojson and lsp libraries in the analysis library
    ##8436
  • Remove global state Shared_types.state
    #8465

@codecov

codecov Bot commented May 22, 2026 •

Copy link
Copy Markdown

Welcome to Codecov 🎉

Once you merge this PR into your default branch, you're all set! Codecov will compare coverage reports and display results in all future pull requests.

Thanks for integrating Codecov - We've got you covered ☂️

@pkg-pr-new

pkg-pr-new Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

rescript

npm i https://pkg.pr.new/rescript@8425

@rescript/belt

npm i https://pkg.pr.new/@rescript/belt@8425

@rescript/darwin-arm64

npm i https://pkg.pr.new/@rescript/darwin-arm64@8425

@rescript/linux-arm64

npm i https://pkg.pr.new/@rescript/linux-arm64@8425

@rescript/linux-x64

npm i https://pkg.pr.new/@rescript/linux-x64@8425

@rescript/runtime

npm i https://pkg.pr.new/@rescript/runtime@8425

@rescript/win32-x64

npm i https://pkg.pr.new/@rescript/win32-x64@8425

commit: cd7dbf8

fhammerschmidt added a commit that referenced this pull request Jun 22, 2026
* Omit empty document symbol children

DocumentSymbol.children is optional, so only set it when a symbol has nested entries. This avoids serializing leaf symbols with an empty children array.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>

* add transform_opt for server-side use

* analysis: add state_to_yojson

* packages: add dependencies

* Update CHANGELOG.md

* Apply codex review suggestions

* Refactor cmt_viewer.dump for serve-side

* Analysis cmt dump return a string instead a option

---------

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Co-authored-by: Florian Hammerschmidt <florianh89@gmail.com>
@github-actions

Copy link
Copy Markdown

Semantic Diff

1 new commit (128 total) · Full page

implement test e2e

c65e5d1 · Pedro Castro · Aug 02, 2026

@github-actions

Copy link
Copy Markdown

Semantic Diff

1 new commit (129 total) · Full page

update yarn.lock

2863c1c · Pedro Castro · Oct 23, 2026

@github-actions

Copy link
Copy Markdown

Semantic Diff

1 new commit (130 total) · Full page

remove lsp from rust rewatch

0ee23ac · Pedro Castro · Oct 23, 2026

@github-actions

Copy link
Copy Markdown

Semantic Diff

1 new commit (131 total) · Full page

update makefile lsp tests

45e23a9 · Pedro Castro · Oct 23, 2026

@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Changelog

🚀 New Feature

  • Add an experimental ReScript language server bundled with the compiler, available
    through rescript lsp --stdio. It reuses compiler analysis for hover,
    completion, navigation, rename, diagnostics, formatting, and code actions.

Semantic Diff

168 commits · Full page

initial lsp

cbf971e · aspeddro · Dec 01, 2024, 15:31 UTC

update

9767c9f · aspeddro · Apr 29, 2026, 03:06 UTC

add state

b1b4b04 · aspeddro · Apr 30, 2026, 12:13 UTC

Extract server I/O into Server module and simplify handlers

d09d328 · aspeddro · May 12, 2026, 01:02 UTC

- Move Io, Chan, and listen infrastructure to server.ml - Simplify on_request to take a packed request directly - Add basic hover response with markdown content - Rename public executable to rescript-language-server

Add parse_implementation_from_source and refactor LSP server

80e8218 · aspeddro · May 12, 2026, 18:49 UTC

- Add parse_implementation_from_source to parsing/print engine types and all engine implementations, enabling parsing from a string source rather than a filename - Use parse_implementation_from_source in CompletionFrontEnd - Rename package from rescript-lsp to rescript-language-server - Refactor LSP server with typed state, document store, and diagnostics - Add hover support via completion backend integration

Split LSP into bin/src layout and add hover integration test

ad0b764 · aspeddro · May 14, 2026, 08:11 UTC

Move LSP modules under lsp/src/ with a thin lsp/bin/ entry point, add a configuration module, and introduce a tests/lsp_tests workspace exercising hover end-to-end.

Refactor analysis to decouple I/O from core logic

5a36dd1 · aspeddro · May 16, 2026, 02:53 UTC

Splits Commands.ml into a pure layer that returns OCaml values (option, list, typed records like Protocol.hover, Protocol.signatureHelp, Protocol.completionItem) and a new analysis/src/Cli.ml that does the stringify-and-print step. analysis/bin/main.ml now dispatches to Cli.*, while the LSP server consumes Commands.* directly.

Makes the parsers accept source strings: res_driver gains parse_interface_from_source alongside the existing parse_implementation_from_source

Delegate hover logic to Analysis.Commands.hover

9276f9e · aspeddro · May 16, 2026, 02:54 UTC

Rename tokenModifiersString to tokenModifiers with correct type

1c9f4b4 · aspeddro · May 16, 2026, 03:53 UTC

Update dune-project

56563c2 · aspeddro · May 22, 2026, 13:17 UTC

Refactor LSP test infrastructure

104bb77 · aspeddro · May 31, 2026, 20:39 UTC

- Rename Helper module to Client - Move expected output files into workspace directories - Improve request log format to show file path:line:col - Simplify hover.ml by removing intermediate result binding - Disable in-source compilation for basic-workspace

ci: add linux-headers

555bb76 · aspeddro · May 31, 2026, 21:06 UTC

ci: add linux-headers-generic

e8e3dc0 · aspeddro · May 31, 2026, 21:19 UTC

ci: linux-libc-dev

c0bdf8b · aspeddro · May 31, 2026, 21:57 UTC

ci: add build-essential

4e26483 · aspeddro · May 31, 2026, 22:11 UTC

ci: add build-essential and linux-libc-dev

dafb3d9 · aspeddro · May 31, 2026, 23:16 UTC

ci: update cache version to v5

682137e · aspeddro · May 31, 2026, 23:30 UTC

ci: make Linux headers visible to musl-gcc

ee3f8ad · aspeddro · Jun 01, 2026, 23:26 UTC

ci: support arm and disable test for build for ocaml 5.0

91f82e4 · aspeddro · Jun 01, 2026, 23:56 UTC

makefile: add test-lsp

921ee2c · aspeddro · Jun 02, 2026, 01:13 UTC

Add LSP compiler diagnostics and file watching

b556990 · aspeddro · Jun 05, 2026, 20:35 UTC

Parse ReScript compiler logs into LSP diagnostics and keep diagnostic state in the language server so stale entries can be cleared when logs change. Read build roots from .sourcedirs.json to support monorepos and refresh diagnostics across all compiler logs instead of only the changed watch path.

Register dynamic workspace/didChangeWatchedFiles watchers after the client sends initialized, and add server-side request/response tracking so client responses to server requests no longer crash the input loop.

Tighten document store errors, thread the Eio environment through server state, update hover handling to use the current analysis API, and extend LSP tests to initialize the server before running workspace requests.

Comment to add more compiler log test

6c1c18d · aspeddro · Jun 06, 2026, 16:37 UTC

ci: add lsp test step

337066d · aspeddro · Jun 06, 2026, 16:41 UTC

fix opam install ppx_expect

9b86e9d · aspeddro · Jun 06, 2026, 16:51 UTC

ppx_expect uses Jane Street-style opam versions like v0.17.2, not 0.17.2

ci: run test inside opam opam exec --

b6566fd · aspeddro · Jun 06, 2026, 17:12 UTC

lsp: disable hover supports_markdown_links for now

350aaa7 · aspeddro · Jun 06, 2026, 17:27 UTC

Move Eio_main setup to LSP executable

0461d57 · aspeddro · Jun 06, 2026, 18:05 UTC

Keep the language server library independent from Eio_main by exposing a listen function that accepts input, output, and filesystem handles. Store only the filesystem handle in LSP state and remove the unused environment from the server record.

ci: skip lsp tests on Windows

7ac8f90 · aspeddro · Jun 06, 2026, 18:21 UTC

Expand LSP request handling and diagnostics

3e1cde6 · aspeddro · Jun 07, 2026, 03:50 UTC

Advertise and implement the main language server capabilities using the existing analysis commands, including completion, signature help, definition, references, document symbols, code actions, code lenses, inlay hints, semantic tokens, rename, and formatting.

Rework diagnostics so compiler log diagnostics are treated as build snapshots, stale entries are cleared, and syntax diagnostics from the current in-memory document are appended on change. Also make document symbols source-based so the LSP can serve open documents without reading from disk.

Enforce LSP server lifecycle

126f691 · aspeddro · Jun 07, 2026, 18:51 UTC

Track initialize, running, and shutdown states in the LSP server loop. Reject requests before initialization with ServerNotInitialized, reject requests after shutdown with InvalidRequest, and allow exit notifications to terminate with the correct status code.

Also make unsupported requests and notifications explicit in the language server handlers.

analysis refactor: remove global state Shared_types.state

2bcd8dc · aspeddro · Jun 07, 2026, 20:10 UTC

lsp: use analysis state

5127e6a · aspeddro · Jun 07, 2026, 20:12 UTC

Revert "analysis refactor: remove global state Shared_types.state"

3f6d138 · aspeddro · Jun 08, 2026, 15:19 UTC

This reverts commit bbcb7b9.

analysis: add state_to_yojson

f74e2c9 · aspeddro · Jun 08, 2026, 23:26 UTC

lsp: refactor load_full

688f5cd · aspeddro · Jun 08, 2026, 23:28 UTC

- Add package to server state - Add to_yojson in state

add minimal param to State.to_yojson

2616cc1 · aspeddro · Jun 09, 2026, 02:11 UTC

Makefile: skip test on Windows and update ci

989b85d · aspeddro · Jun 09, 2026, 02:31 UTC

refactor: add discover_subpackages_and_populate

1ea5304 · aspeddro · Jun 10, 2026, 16:11 UTC

fix type error from latest master merge

911cf85 · aspeddro · Jun 10, 2026, 16:15 UTC

Improve LSP workspace initialization and package resolution

967d34e · aspeddro · Jun 10, 2026, 18:41 UTC

Resolve the workspace root from initialize params, initialize analysis state only after the server is initialized, and keep the active package in the initialized server state.

Populate analysis package caches for the workspace and dependencies. Resolve document requests against the package whose root best matches the document path, so nested package workspaces use the correct package metadata.

Implement code_actions.ml

0853d3c · aspeddro · Jun 13, 2026, 12:27 UTC

lsp format: use rescript format command

12d2e75 · aspeddro · Jun 13, 2026, 20:04 UTC

Add code actions from compiler log

a4635e3 · aspeddro · Jun 13, 2026, 22:51 UTC

Add LSP configuration handling

dc2d30f · aspeddro · Jun 14, 2026, 01:31 UTC

Pull workspace configuration from the client and decode it into typed server settings for hover, code lens, inlay hints, and signature help behavior.

Route server-initiated request responses through an on_response handler so configuration updates do not block the LSP input loop

Circular dependency diagnostics: expand end character

d9308a1 · aspeddro · Jun 14, 2026, 01:54 UTC

Add LSP compiler config parsing

5759740 · aspeddro · Jun 14, 2026, 23:46 UTC

add code actions and custom requests

a31d367 · aspeddro · Jun 14, 2026, 23:46 UTC

fix dune tests

fe72544 · aspeddro · Jun 14, 2026, 23:48 UTC

code action: check for window/showDocuent support

71829e3 · aspeddro · Jun 15, 2026, 03:13 UTC

Add LSP file navigation commands

42f097a · aspeddro · Jun 16, 2026, 00:37 UTC

Add code actions and execute commands for opening compiled output, creating interface files, switching between implementation/interface files, and dumping server state. Centralize filesystem access through option-based Eio helpers so LSP paths can be checked without raising.

chore: renames and minor fixes

aa66d0e · aspeddro · Jun 16, 2026, 01:11 UTC

add todo comments and minor fixes

a6645f6 · aspeddro · Jun 16, 2026, 01:24 UTC

add lsp.md

fe3e496 · aspeddro · Jun 16, 2026, 01:29 UTC

Update lsp.md

dddcf27 · aspeddro · Jun 16, 2026, 02:56 UTC

Omit empty document symbol children

a0a9226 · aspeddro · Jun 17, 2026, 15:40 UTC

DocumentSymbol.children is optional, so only set it when a symbol has nested entries. This avoids serializing leaf symbols with an empty children array.

Fix lsp document symbol

f0c9b00 · aspeddro · Jun 17, 2026, 15:41 UTC

Update lsp.md

e547876 · aspeddro · Jun 17, 2026, 15:41 UTC

Add server notification rescript/compilationFinished

7bda550 · aspeddro · Jun 17, 2026, 23:45 UTC

compiler_log: add warning number

43869d9 · aspeddro · Jun 17, 2026, 23:59 UTC

add warning number in diagnostic message

d9dba17 · aspeddro · Jun 18, 2026, 00:07 UTC

Add more test to compiler log parser

6078f60 · aspeddro · Jun 18, 2026, 01:42 UTC

Add cli

691c2fb · aspeddro · Jun 18, 2026, 02:18 UTC

fix Neovim bug document symbol

5ec4d65 · aspeddro · Jun 19, 2026, 01:35 UTC

minimal refactor on rescript_language_server.ml

2872ed5 · aspeddro · Jun 19, 2026, 01:36 UTC

support workspace/codeLens/refresh

f059445 · aspeddro · Jun 19, 2026, 03:24 UTC

Resolve runtime packages from workspace node_modules

fa21eec · aspeddro · Jun 19, 2026, 14:28 UTC

Prefer package-manager installs under the active workspace when resolving dependencies, including Deno and pnpm node_modules layouts.

Keep Runtime_package.path as a compiler-development fallback so editor navigation does not jump from user projects into the server checkout.

build system: remove RESCRIPT_RUNTIME env var

434d5b8 · aspeddro · Jun 19, 2026, 14:29 UTC

Make Configuration unstrict

0036ae7 · aspeddro · Jun 19, 2026, 20:26 UTC

add more log message for invalid settings

763f61d · aspeddro · Jun 19, 2026, 20:28 UTC

dump server state: add configuration and order elements

714af2c · aspeddro · Jun 19, 2026, 20:29 UTC

Server request settings from item rescript.settings

9dc1bfc · aspeddro · Jun 19, 2026, 20:30 UTC

move Exit to end

1518254 · aspeddro · Jun 19, 2026, 20:30 UTC

Support TextDocumentDiagnostic and improve TextDocumentDidOpen

5138750 · aspeddro · Jun 19, 2026, 21:20 UTC

Publish syntax error diagnostic on open document

Keep diagnostic sources separate

113df9f · aspeddro · Jun 19, 2026, 22:02 UTC

Track compiler diagnostics, compiler syntax diagnostics, and open-document syntax diagnostics independently so each source can be refreshed according to its own lifetime.

A syntax-only compiler log is an incomplete build snapshot, so keep existing type diagnostics until the next complete compiler snapshot or successful empty log. Open documents continue to use in-memory syntax diagnostics, while closed documents can fall back to compiler syntax diagnostics.

Use sourcedirs for initial compiler diagnostics

2889b5a · aspeddro · Jun 19, 2026, 22:17 UTC

Read diagnostics from the compiler-log roots recorded in .sourcedirs.json so opening a document can publish the last known compiler diagnostics even when the compiler is not currently running.

Keep the root lib/bs/.compiler.log fallback only for older or partial builds without sourcedirs metadata, and document the diagnostic behavior and release notes.

remove double newline from message diagnostic

632dcec · aspeddro · Jun 19, 2026, 22:33 UTC

update analysis tests

223c421 · aspeddro · Jun 19, 2026, 22:34 UTC

refactor compiler log parser

def48a0 · aspeddro · Jun 20, 2026, 00:16 UTC

cli, print to stderr

9ff490c · aspeddro · Jun 20, 2026, 01:29 UTC

refactor compiler log to use option for range

d633159 · aspeddro · Jun 20, 2026, 01:41 UTC

Update compiler log tests snapshots

78c3e21 · aspeddro · Jun 20, 2026, 12:13 UTC

Update compiler_config.ml

1e95aab · aspeddro · Jun 20, 2026, 12:14 UTC

Remove comment from code_actions.ml

5808d26 · aspeddro · Jun 20, 2026, 12:14 UTC

Avoid duplicate syntax diagnostics on document changes

e340e40 · aspeddro · Jun 20, 2026, 14:13 UTC

Do not push open-buffer syntax diagnostics through textDocument/publishDiagnostics on didChange. They are already available through textDocument/diagnostic.

Keep the changed URI force-published so any stale pushed syntax diagnostics are cleared when the filtered diagnostic set is empty.

minor fixes: add todo comment and fix typos in messages

08b6557 · aspeddro · Jun 20, 2026, 14:14 UTC

workspace/configuration section must use rescript

c14de44 · aspeddro · Jun 20, 2026, 15:47 UTC

Improve todo comments

ee9331e · aspeddro · Jun 20, 2026, 17:04 UTC

Update lsp.md

96505e1 · aspeddro · Jun 20, 2026, 17:21 UTC

Update lsp.md

3247c2d · aspeddro · Jun 20, 2026, 17:27 UTC

Refactor cmt_viewer.dump for serve-side

3cb3190 · aspeddro · Jun 20, 2026, 22:04 UTC

Refactor execute commands. Move logic to module execute_commands.ml

66200a1 · aspeddro · Jun 21, 2026, 00:12 UTC

Move format logic to module Formatter.ml

5a696e4 · aspeddro · Jun 21, 2026, 00:23 UTC

Refactor code, better error messages

0efba12 · aspeddro · Jun 21, 2026, 01:52 UTC

Analysis cmt dump return a string instead a option

207a05f · aspeddro · Jun 21, 2026, 01:52 UTC

Update lsp.md

4c1d668 · aspeddro · Jun 21, 2026, 01:53 UTC

minor fixes

adeef92 · aspeddro · Jun 21, 2026, 02:45 UTC

minor refactor

eaca209 · aspeddro · Jun 21, 2026, 16:26 UTC

fix typo: Unknow -> Unknown

62aadc8 · aspeddro · Jun 30, 2026, 14:04 UTC

code actions: use %todo

3d32ad6 · aspeddro · Jun 30, 2026, 14:07 UTC

Update lsp.md

e7e4edd · aspeddro · Jun 30, 2026, 14:16 UTC

Update lsp.md

7ecb29e · aspeddro · Jun 30, 2026, 14:16 UTC

lsp.md: fix typos

dcbb246 · aspeddro · Jun 30, 2026, 14:33 UTC

Add rescript_language_server.mli

9e18966 · aspeddro · Jul 01, 2026, 16:05 UTC

update formatter and lsp.md

5e44b5a · aspeddro · Jul 12, 2026, 02:40 UTC

Resolve some TODOs

b1128cd · aspeddro · Jul 16, 2026, 23:55 UTC

Restore get_runtime_dir in build_system.ml

ab13d92 · aspeddro · Jul 17, 2026, 00:26 UTC

Resolve todo resolve dep resolution using analysis

2124bc0 · aspeddro · Jul 17, 2026, 01:02 UTC

Remove signature help setting. Enable by default

0880539 · aspeddro · Jul 17, 2026, 01:22 UTC

Replace command rescript-vscode.go_to_location with native URls

b1d3224 · aspeddro · Jul 17, 2026, 02:00 UTC

file://name.res#LX,Y

Works in VSCode and Zed!!

Update lsp.md

c2b3660 · aspeddro · Jul 17, 2026, 02:01 UTC

Restore step ci Make Linux headers visible to musl-gcc

7413dc4 · aspeddro · Jul 17, 2026, 02:07 UTC

Update action.yml

0b6206e · aspeddro · Jul 17, 2026, 02:20 UTC

Restore version in action.yml

983c968 · aspeddro · Jul 17, 2026, 02:47 UTC

Fix uring install on ci

6b53a89 · aspeddro · Jul 17, 2026, 02:47 UTC

Update lsp.md and add notes.md

592a731 · aspeddro · Jul 17, 2026, 12:17 UTC

Integrate lsp command into Rewatch

e9a47cc · aspeddro · Jul 17, 2026, 15:16 UTC

Make binary statically linked

6d3d8a5 · aspeddro · Jul 17, 2026, 18:39 UTC

Fix stale and flickering LSP diagnostics

5e320a4 · aspeddro · Jul 25, 2026, 02:32 UTC

Merge all diagnostic sources when serving requests and serializing state. Ignore partial compiler logs until #Done, then publish the completed snapshot and refresh pull diagnostics so clients clear resolved warnings without flickering.

add lsp in COMPILER_SOURCES

f2caebc · aspeddro · Jul 25, 2026, 02:33 UTC

fix duplicated diagnostic

51be468 · aspeddro · Jul 25, 2026, 03:12 UTC

Update test.ml

977c321 · aspeddro · Jul 25, 2026, 03:13 UTC

Fix formatter

14fcdfd · aspeddro · Jul 25, 2026, 06:20 UTC

Refactor document store to use incremental text change

4f1261e · aspeddro · Jul 26, 2026, 00:55 UTC

Fix neovim bug in test dev

0a6bc45 · aspeddro · Jul 26, 2026, 00:56 UTC

Update lsp.md

24e0e34 · aspeddro · Jul 26, 2026, 01:11 UTC

Add Document.extension_of_kind

0f17da8 · aspeddro · Jul 31, 2026, 18:02 UTC

test: enable tests on windows using Unix.open_process_args

74bdab7 · aspeddro · Jul 31, 2026, 18:22 UTC

implement test e2e

11f17cb · aspeddro · Aug 02, 2026, 18:40 UTC

update yarn.lock

17d694e · aspeddro · Oct 23, 2026, 14:22 UTC

remove lsp from rust rewatch

ba2141e · aspeddro · Oct 23, 2026, 14:36 UTC

update makefile lsp tests

7153a6e · aspeddro · Oct 23, 2026, 15:34 UTC

add hover test

e612509 · aspeddro · Oct 23, 2026, 17:07 UTC

Add more lsp tests

a9e7508 · aspeddro · Oct 24, 2026, 14:43 UTC

Add full tests

cc126b8 · aspeddro · Oct 24, 2026, 15:00 UTC

Move lsp entrypoint to rewatch-ocaml

3e2a095 · aspeddro · Oct 24, 2026, 22:19 UTC

Fix module shadow

d0d935c · aspeddro · Oct 24, 2026, 22:31 UTC

Remove packages/@rescript/darwin-x64

97485ad · aspeddro · Oct 24, 2026, 22:36 UTC

Remove rescript_language_server_exe binary from bin.js files

25c8ea8 · aspeddro · Oct 24, 2026, 22:37 UTC

Fix dune runtest

7041f86 · aspeddro · Oct 24, 2026, 22:55 UTC

Restore lsp tests on CI

b4367d4 · aspeddro · Oct 25, 2026, 22:26 UTC

Restore test-rewatch-rust rule in makefile

7ae1e3d · aspeddro · Oct 25, 2026, 22:35 UTC

write file for dump cmt and server state

defa136 · aspeddro · Oct 26, 2026, 15:56 UTC

Update lsp.md and notes.md

ed86dbb · aspeddro · Oct 26, 2026, 16:12 UTC

Update hover_jsx.ml

f010956 · aspeddro · Oct 26, 2026, 16:59 UTC

Fix Analysis.Create_interface.command

5be287b · aspeddro · Oct 31, 2026, 17:03 UTC

Disable workspaceFolders

b499a88 · aspeddro · Oct 31, 2026, 17:03 UTC

Remove comment interFileDependencies

a6edb10 · aspeddro · Oct 31, 2026, 17:03 UTC

Recover the LSP analysis context after a workspace build

b7147d1 · aspeddro · Oct 31, 2026, 17:19 UTC

Why

Projects opened before their first build lack generated metadata. Recover on compiler-log events without requiring an editor restart.

Context modified (compiler-log creation and change notifications)

text

-Refresh diagnostics using the existing analysis and package context.
+Discover fresh analysis tables and package configuration.
+Replace the context if the workspace package is available.
+Otherwise retain the previous context without repeated error messages.
+Preserve open buffers, settings and diagnostics, then refresh diagnostics.

Diagnostic modified (initial package discovery failure)

text

-Try building the project then restart the server
+Try building the project. The server will retry when a compiler log
+changes.

Add snapshot tests for Created and Changed events, early retries, compiled-file lookup and preservation of unsaved buffers. Document the automatic recovery behavior.

Update tests

fec7da9 · aspeddro · Oct 31, 2026, 17:46 UTC

Remove uri.mli, package.json entry and

f2e3a7a · aspeddro · Oct 31, 2026, 17:54 UTC

changes/opam-ppx-expect.internal.md

Add position_encoding option in state

2152e00 · aspeddro · Oct 31, 2026, 21:03 UTC

Fixed helpers.ml: the source extension is removed before appending the

93bec6c · aspeddro · Oct 31, 2026, 21:13 UTC

namespace, producing Test-MyPackage.cmi

Resolve compiled JavaScript and interface artifacts using the requested

406f62c · aspeddro · Oct 31, 2026, 21:42 UTC

document's package configuration instead of the workspace root's settings.

Fixed: a nonempty workspaceFolders list now selects its first folder

e440b15 · aspeddro · Oct 31, 2026, 21:47 UTC

independently of rootUri and rootPath. Fallback to Sys.getcwd

Add position_encoding in State.to_yojson

2611be3 · aspeddro · Oct 31, 2026, 21:52 UTC

Close formatter pipes and reap the child process when formatting fails,

427f2db · aspeddro · Oct 31, 2026, 22:12 UTC

relying on the ReScript formatter to report syntax errors.

Add CHANGELOG fragment

6c444d4 · aspeddro · Oct 31, 2026, 22:16 UTC

improve formatter

2d50911 · aspeddro · Nov 02, 2026, 03:46 UTC

Support lib/rescript folder

9c6a69b · aspeddro · Nov 06, 2026, 23:36 UTC

delete old lib/{bs,ocaml} folder

ea5c409 · aspeddro · Nov 07, 2026, 00:02 UTC

delete github workflows ci yamls

4e07c14 · aspeddro · Nov 07, 2026, 00:04 UTC

delete .orig files

4f81def · aspeddro · Nov 07, 2026, 00:05 UTC

delete rewatch-ocaml/README.md.orig

4209bd4 · aspeddro · Nov 07, 2026, 00:07 UTC

Update ci

16bd533 · aspeddro · Nov 07, 2026, 02:03 UTC

Remove compatibility field

11ba488 · aspeddro · Nov 07, 2026, 03:06 UTC

Document the OCaml language server architecture, diagnostic ownership, configuration, limitations, and test workflow in

e700b6b · aspeddro · Nov 07, 2026, 03:07 UTC

✨ Add LSP expect tests for Temporal and typed-array completion, generic

2645b50 · aspeddro · Nov 07, 2026, 03:30 UTC · new

JSX, existential hover, record-rest patterns, and namespaced references.

Update ci

79fc35b · aspeddro · Nov 07, 2026, 03:33 UTC

@aspeddro

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-26T16:13:47.910529Z 954d894 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

aspeddro added a commit to aspeddro/rescript-compiler that referenced this pull request Oct 31, 2026
* Omit empty document symbol children

DocumentSymbol.children is optional, so only set it when a symbol has nested entries. This avoids serializing leaf symbols with an empty children array.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>

* add transform_opt for server-side use

* analysis: add state_to_yojson

* packages: add dependencies

* Update CHANGELOG.md

* Apply codex review suggestions

* Refactor cmt_viewer.dump for serve-side

* Analysis cmt dump return a string instead a option

---------

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Co-authored-by: Florian Hammerschmidt <florianh89@gmail.com>
Signed-off-by: Pedro Castro <aspeddro@gmail.com>
@aspeddro

Copy link
Copy Markdown
Contributor Author

Codex review using GPT 6 Astra Ultra


The new server has position-encoding and initialization compatibility bugs, incorrect package artifact resolution, and a formatter process leak. These affect ordinary editor workflows and require correction.

Full review comments:

  • [P1] Negotiate position encoding before interpreting document edits — /home/pedro/Desktop/projects/rescript-compiler/lsp/src/document.ml:28-30
    Documents unconditionally interpret positions as UTF-8, but the initialize response omits positionEncoding, which means UTF-16 in LSP. Consequently, edits after non-ASCII characters can modify the wrong bytes or be silently rejected, and analysis locations are misaligned. Negotiate the encoding with the client and convert positions consistently, including supporting the mandatory UTF-16 fallback.

  • [P2] Append the namespace after removing the source extension — /home/pedro/Desktop/projects/rescript-compiler/lsp/src/helpers.ml:131-133
    For a namespaced source such as Test.res, this constructs Test.res-MyPackage and then removes .res-MyPackage, yielding Test.cmi instead of Test-MyPackage.cmi. Interface creation therefore cannot find the compiled interface in namespaced projects. Remove the source extension before appending the namespace suffix.

  • [P2] Select output configuration from the requested document — /home/pedro/Desktop/projects/rescript-compiler/lsp/src/helpers.ml:156-161
    When a document belongs to a discovered dependency or nested package, this selects the workspace root's configuration rather than that document's package configuration. If the packages have different suffixes, module formats, or in-source settings, opening compiled JavaScript looks in the wrong location despite the output existing. Match against Uri.to_path uri here and in the analogous configuration lookup in get_cmi_file.

  • [P2] Accept workspace folders without a legacy root URI — /home/pedro/Desktop/projects/rescript-compiler/lsp/src/helpers.ml:5-6
    A valid initialize request can supply a nonempty workspaceFolders list while leaving the deprecated rootUri and rootPath null. This pattern requires rootUri as well, so such requests fall through to failwith, terminating initialization instead of using the supplied workspace folder. Handle a nonempty folder list independently of the legacy fields.

  • [P2] Validate syntax before spawning the formatter — /home/pedro/Desktop/projects/rescript-compiler/lsp/src/formatter.ml:66-69
    Formatting a document with a syntax error reaches this branch after Unix.open_process_args has already started the formatter, but returns without closing either pipe or reaping the child. Repeated format requests on incomplete code accumulate processes and descriptors. Perform the syntax check before spawning, or guarantee cleanup on this branch too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This change makes analysis prefer the runtime installed in the project over the compiler-local runtime.

Previously, resolving @rescript/runtime bypassed the normal node_modules search and immediately returned Runtime_package.get_path (). During local LSP development, this could make “Go to definition” open runtime sources from the compiler checkout instead of the user’s project.

The resolver now searches the project and its ancestor directories first, including the .deno/node_modules and .pnpm/node_modules lookup locations. The compiler-local runtime remains a fallback for development environments where the project has no runtime installation.

This is not a complete Node/Deno/pnpm module resolver; it extends the existing package-directory lookup. The explicit RESCRIPT_RUNTIME override still takes precedence when selecting the analysis runtime.

Module resolution searches each directory and its ancestors for:

  1. node_modules/<package>
  2. node_modules/.deno/node_modules/<package>
  3. node_modules/.pnpm/node_modules/<package>

Comment thread .github/workflows/ci.yml
# first linux-x64 job runs them.
- os: ubuntu-24.04
ocaml_compiler: ocaml-variants.5.0.0+options,ocaml-option-static
ocaml_compiler: ocaml-variants.5.3.0+options,ocaml-option-static

@aspeddro aspeddro Nov 7, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The CI compatibility job now uses OCaml 5.3 instead of 5.0 because the current test dependencies cannot be resolved on 5.0.

The compiler requires ppxlib >= 0.38.0. The language server’s ppx_expect dependency pulls in Jane Street PPXs whose versions compatible with that ppxlib require OCaml 5.3 or newer.

@aspeddro
aspeddro marked this pull request as ready for review November 7, 2026 03:19
@github-actions

github-actions Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Changelog

🚀 New Feature

  • Add an experimental ReScript language server bundled with the compiler, available
    through rescript lsp --stdio. It reuses compiler analysis for hover,
    completion, navigation, rename, diagnostics, formatting, and code actions.

Semantic Diff

12 commits · Full page

Add the OCaml ReScript language server

28020ee · aspeddro · Nov 23, 2026, 13:16 UTC

Ship the language server with the compiler so editor analysis uses the matching compiler metadata instead of a separately versioned executable. Consolidate the initial implementation, tests, documentation, and build integration while retaining the upstream master history.

Command added (language-server entrypoint)

text

-rescript: build, watch, clean, format, compiler-args
+rescript: build, watch, clean, format, compiler-args, lsp --stdio
+The lsp subcommand runs the OCaml server over stdio using Eio.

Connect LSP requests to the in-tree analysis library. Track editor syntax and compiler diagnostics separately, refresh analysis after builds, and provide configuration, navigation, interface creation, and debug commands.

Add cross-platform stdio expect tests, editor setup documentation, CI integration, and third-party license notices for the linked dependencies.

✏️ Add --clientProcessId argument in lsp subcommand

6c3b7b0 · aspeddro · Nov 17, 2026, 02:15 UTC · edited

Accept the positive client PID that some editors append automatically so their standard launch command works. Keep --stdio mandatory and leave process monitoring outside this compatibility option.

Command modified (LSP client compatibility)

text

-rescript lsp --stdio --clientProcessId 123: rejected
+rescript lsp --stdio --clientProcessId 123: accepted
+The PID must be a positive integer and is not monitored.

Update CLI parsing tests and help snapshots for the optional argument.

Keep the language server running after invalid input

46e18ef · aspeddro · Nov 22, 2026, 22:02 UTC

Why

A malformed message or handler exception could terminate the server, interrupting unrelated editor requests.

Protocol modified (message error recovery)

text

-Malformed input: terminate the server.
-Request exception: terminate the server.
-Notification exception: terminate the server.
+Malformed input: skip it and continue reading.
+Request exception: return a JSON-RPC error and retain session state.
+Notification exception: log to stderr and continue reading.

Diagnostic modified (document store)

diagnostic

-InvalidRequest: Document store not found <uri> to get
+RequestFailed: Cannot get document <uri>: it is not open.

Add end-to-end snapshots for error recovery, state preservation, and clean shutdown. Capture subprocess stderr and preserve actual exit codes.

Verified with dune runtest and make dead-code.

✏️ Back to InvalidParams

4f3d55f · aspeddro · Nov 22, 2026, 22:07 UTC · edited

Request parameter decoding failures describe invalid client input, not internal server failures. Return the appropriate JSON-RPC error code and update the protocol regression snapshot, retaining the initialized state.

Protocol modified (invalid request parameters)

text

-Invalid hover parameters -> InternalError (-32603)
+Invalid hover parameters -> InvalidParams (-32602)
Read large LSP message bodies in bounded chunks

eedb5d9 · aspeddro · Nov 22, 2026, 22:21 UTC

Why

Reading an entire body through the 1 MiB input buffer rejected large documents and left the server unable to process later messages.

Protocol modified (message body reads)

text

-Read the entire Content-Length body in one buffered operation.
-Bodies larger than 1 MiB exceed the reader limit.
+Keep direct reads for bodies up to 1 MiB.
+Assemble larger bodies from chunks no larger than 1 MiB.
+Consume exactly Content-Length bytes, preserving the next header.

Add regression tests for opening and editing documents over 2 MiB, including subsequent requests to verify message framing remains intact.

Verified with dune runtest, make dead-code, and changelog validation.

Offer the create-interface code action for implementations without an interface

ae00b14 · aspeddro · Nov 22, 2026, 22:51 UTC

Advertise its command, and refuse to overwrite existing interface files

Format editor buffers without requiring a workspace-local rescript executable

a6d5a95 · aspeddro · Nov 22, 2026, 23:07 UTC

- Leave documents with syntax errors unchanged without error popups.

✏️ Format code

51b3d2f · aspeddro · Nov 22, 2026, 23:17 UTC · edited

Normalize the language-server library's dependency list to Dune's compact formatting. This changes no dependencies or build behavior.

Give language-server commands unique per-instance IDs so multiple ReScript

956b7ef · aspeddro · Nov 22, 2026, 23:37 UTC

- Projects can initialize in the same VS Code window. Plain command names remain supported for direct client calls.

Fix bug reported in #8425 (comment)

Fix Windows drive-case mismatches in LSP diagnostics

df1ec78 · aspeddro · Nov 22, 2026, 23:46 UTC

Why

Compiler logs and editors can use different drive-letter casing. Structural URI comparison treats these as separate documents, causing compiler errors to disappear when a file opens.

Representation modified (document and diagnostic keys)

text

-D:/project/Broken.res and d:/project/Broken.res use separate keys.
-Pull diagnostics for the open document return an empty list.
+Serialized URI keys identify both paths as the same document.
+Pull diagnostics retain compiler errors.
+Filename case remains distinct.

Add unit and end-to-end regressions for URI lookup, diagnostic merging, open/close ownership, and clearing errors after a clean build. Document the unchanged pull behavior for documents without an editor.

Reuse rewatch configuration decoding in the language server

d677748 · aspeddro · Nov 23, 2026, 00:18 UTC

Why

The LSP maintained a separate rescript.json decoder whose defaults and namespace rules could diverge from the build system.

Representation modified (project configuration)

text

-The LSP decodes its own partial schema and computes artifact paths.
-Missing package-specs defaults to CommonJS out-of-source output.
+Config.of_string decodes Eio-loaded contents using the build schema.
+Rewatch helpers resolve namespaces and generated artifact paths.
+Missing package-specs uses the build's ES module in-source default.

Keep ppx_deriving_yojson for editor settings and decode source-directory metadata with Yojson directly. Update documentation and license scopes.

Add tests for decoder parity, output defaults, multiple outputs, namespaces, settings validation, and malformed source-directory metadata.

Move LSP inline tests into a dedicated test library

51aea94 · aspeddro · Nov 23, 2026, 04:11 UTC

Keep ppx_expect and its transitive runtimes out of the shipped rescript binary by moving all 13 inline tests to tests/lsp_unit_tests.

Extract rescript_language_server_core so tests exercise the production implementation while preserving the existing listen interface. Run both LSP suites through make test-lsp and update the documentation.

Remove the unlinked test dependencies from the license inventory and regenerate the third-party notices

@cknitt

cknitt commented Nov 16, 2026

Copy link
Copy Markdown
Member

Thanks for this, @aspeddro! Running the analysis code in-process behind rescript lsp --stdio makes a lot of sense to me. I have some design questions first, then a list of bugs.

The bug list comes from a review by Claude (at 00aaba1). Claude read the code, built the PR on linux-arm64 (OCaml 5.5.2), and checked each finding with a small LSP client against rescript lsp --stdio. tests/lsp_tests and the inline tests pass. "Reproduced" below means Claude saw it happen. Points Claude could not test say so.

Design

1. Dependencies

The PR adds a lot of new dependencies (about 30 new license entries). I don't think all of them are needed:

  • lsp (with jsonrpc, ppx_yojson_conv_lib, uutf): worth keeping. Its runtime dependencies are small, and its UTF-16 edit handling works (Claude tested it with é and emoji).

  • eio, eio_main (with eio_linux, uring, eio_posix, iomux, cstruct, mtime and others): as far as I can see, they are used for:

    • reading stdin and writing stdout behind a mutex;
    • five file calls in fs.ml;
    • starting the formatter process (not needed, see the formatting point below);
    • a promise wrapper (Io.async).

    Nothing runs concurrently: input_loop waits for each message before reading the next one. Plain Stdlib/Unix would do. If we need an event loop later, rescript already links luv (libuv) for watch mode. Eio adds a second event loop and needs OCaml 5.2.

  • ppx_deriving_yojson: only used to decode 8 record types (rescript.json, .sourcedirs.json, settings). rewatch-ocaml already decodes rescript.json (config_decode.ml), and so does analysis. I'd rather reuse one of those than add a third parser.

  • ppx_expect: only needed for tests, but (inline_tests) in lsp/src/dune links Base, ppxlib, Sexplib0 and Stdio into the shipped rescript binary, about 1.1 MB. It is also why CI needs OCaml 5.3 (ppxlib_jane requires it), while dune-project says >= 5.0.0. Could the inline tests move to a library under tests/?

Without these, the new runtime dependencies would be just lsp, jsonrpc, ppx_yojson_conv_lib and uutf. For scale: the stripped rescript.exe is 30.4 MB with this PR, against 16.5 MB on master.

2. Where the data comes from

Right now everything is read from disk after the build wrote it:

  • Diagnostics: the .compiler.log text is parsed back with regexes (compiler_log.ml, 1.5k lines). The files are found through .sourcedirs.json and re-read when the client reports a log change, and on every didChange.
  • Types for hover, definition and so on: analysis reads .cmt/.cmi files from lib/rescript.
  • Configuration: rescript.json is read through a separate parser.

Keeping the build and the LSP separate, as the PR does, is probably the safer choice, since we had bad experiences with editor integrations that run the watcher. But reading text logs back is fragile, and a later phase could do better while the build stays a separate process:

  • A running rescript watch could send diagnostics as structured data to the LSP, for example over a local socket that the build lock points to. That would remove the log parser and the file watching.
  • The LSP could type-check unsaved buffers in memory, using the compiler already linked into rescript. Today unsaved buffers only get syntax diagnostics.

It would help if the design left room for this now. For example, the diagnostics source and the .cmt source could sit behind a small interface, so they can be replaced later.

Bugs

High

1. One bad message ends the server. Reproduced. In lsp/src/server.ml:201-207, the exception _ arm only covers the read, not with_ state packet. Nothing catches errors from on_request and on_notification. Each of these makes the process exit with code 2:

Message Error on stderr
hover or completion on a file that is not open jsonrpc response error InvalidRequest (-32600)
a second didOpen for the same file same
didClose for a file that is not open same
didOpen of untitled:Untitled-1 (untitled buffer) same
didOpen of a .txt file with languageId rescript same
a body that is not valid JSON Failure("Server.input_loop")
shutdown with "params": null same

Could you wrap each handler and turn exceptions into an error response? For notifications, log the error and keep the old state. This also covers exceptions from analysis. Until now those only ended the analysis process for one request.

2. A request with invalid params resets the state (server.ml:234-237). Reproduced. The Error message branch returns state, which is the initial ~state passed to listen. It should be server.state. A hover without position gets the right InvalidParams answer. But then the next didChange hits Assertion failed at state.ml:40, and the next hover hits it at state.ml:74. Both end the server.

3. Messages larger than 1 MB end the server (server.ml:59-63, max_size:(1024 * 1024)). Reproduced: didOpen of a 1.1 MB file gives Failure("Server.input_loop"). Generated files can be this large.

Medium

  • "Create interface file" is never offered. Reproduced: on a saved Test.res without a .resi, only "Add type annotation" and "Add Documentation template" show up. code_actions.ml:458-461 checks that the .res file is missing instead of the .resi. Also reproduced: textDocument/createInterface overwrites an existing hand-written .resi. And rescript/createInterface is not listed in executeCommandProvider.

  • Formatting starts a second rescript process (formatter.ml:95-100). The server pipes the buffer into <workspace root>/node_modules/.bin/rescript format --stdin. Why? The formatter is already in the same binary: rescript format runs in-process, and Analysis.Commands.format (already on master, used by the analysis CLI) formats a source string with Res_driver and Res_printer. Calling it directly would remove the Process module (about 90 lines with separate Unix and Eio paths) and these reproduced problems:

    • Without node_modules/.bin/rescript at the workspace root, formatting fails with an error popup. That includes a monorepo package opened as the workspace, with .bin at the repo root.
    • A syntax error shows a "Failed to format Test.res" popup on every format.

    On Windows .bin/rescript is a shell shim, so starting it probably fails too (not tested).

  • Each keystroke publishes diagnostics for every known file (rescript_language_server.ml:598-616, diagnostics.ml:100-107). Reproduced: with 100 files that have warnings, each didChange sends 101 publishDiagnostics notifications. On didChange, updating the syntax diagnostics of that one file would be enough.

  • Only the workspace root is a project (rescript_language_server.ml:142-160). Reproduced: with the parent folder of a project as the workspace, hover returns null and two error popups appear. Only the first workspace folder is used. Monorepo packages are registered under node_modules/<pkg>, but Helpers.load_full matches by path prefix. So a file under packages/<pkg>/ may get the root package's namespace (not tested).

  • A missing .sourcedirs.json clears all diagnostics (diagnostics.ml:267-281). Reproduced: a type error is reported while the file exists, and disappears once it is removed. The comment promises a fallback to the root log.

  • I'd drop the module_resolution.ml change. On master, analysis always uses the runtime the compiler uses (Runtime_package.get_path ()). The PR first searches the project's node_modules, .deno and .pnpm folders, and only falls back to the compiler's runtime. As I understand your comment, this fixes "Go to definition" opening runtime sources from the compiler checkout during LSP development. Setting RESCRIPT_RUNTIME already solves that. For users the change has downsides:

    • It also changes rescript-editor-analysis.exe (rescript-vscode) and rescript-tools, through Build_system.get_runtime_dir and Find_files.find_package_root. The second one affects every dependency, not only the runtime.
    • Analysis can end up reading a different runtime than the one the build compiled against. For example, a monorepo package might have its own @rescript/runtime in a nearer node_modules. Or pnpm might hoist another version into .pnpm/node_modules, while the compiler gets its runtime through -runtime-path. That is the kind of version mismatch behind analysis segmentation fault for references after #7887 #8475.
    • resolve_deno_pnpm calls failwith when a package is in both .deno and .pnpm, and only the new server catches it (not tested).
  • Windows paths (not tested). Helpers.relative_to only handles /. Uri comparison is structural, so file:///c%3A/... from VS Code probably does not match the C:\... paths in the compiler log.

Low

  • On EOF without exit, the server exits with 0; the spec says 1 (reproduced).
  • The server registers didChangeWatchedFiles even when the client does not support dynamic registration. Nothing broke in Claude's test, though.
  • $/cancelRequest is ignored and requests run one at a time. That is fine for now, but the README could say so.
  • interFileDependencies: false is not right for compiler diagnostics.
  • lsp/src/dune and tests/lsp_tests/dune override the root warning flags.
  • state_to_yojson in analysis/src/shared_types.ml is only used by rescript/dumpServerState and could live in lsp/.
  • dune-project: the package of the rescript executable does not list eio, eio_main or ppx_deriving_yojson. ppx_expect is :with-test but is needed to build.
  • The custom requests textDocument/openCompiled and textDocument/createInterface could use a rescript/ prefix.

Checked and fine: incremental edits with UTF-16 positions, ServerNotInitialized before initialize, and exit code 0 after a clean shutdown and exit.

Tests

The end-to-end snapshots through the real CLI are a good base. Missing are:

  • the error paths in the table above, and messages over 1 MB;
  • shutdown, exit and exit codes;
  • monorepos, and a workspace that is not the project root;
  • the "Create interface" and "Open compiled" code actions.

Commits

The PR is hard to review in one piece, and its 201 commits need cleaning up anyway (the Semantic Diff check fails because most of them have only a subject line). Could you squash it into a few clean commits, so we can review it step by step? For example:

  1. protocol core, CLI and lifecycle;
  2. requests backed by analysis;
  3. diagnostics;
  4. code actions and custom commands;
  5. licenses and CI.

My priorities: the three high bugs, then the dependency question, then the commit cleanup. Structured data from the watcher and type checking of unsaved buffers can come later.

@fhammerschmidt

Copy link
Copy Markdown
Member

One thing that affects clients that run more than one instance of the server: in VS Code, each ReScript project in a window gets its own rescript lsp process, because projects can pin different compiler versions (and monorepos have several projects). vscode-languageclient registers every command in executeCommandProvider as a global VS Code command. So when a second server starts and announces rescript/openCompiled etc. again, initialization fails with command 'rescript/openCompiled' already exists.

The vscode-languageclient maintainer considers this intended and recommends making the command IDs unique per server instance (microsoft/vscode-languageserver-node#333, #607):

for applyrefact:applyOne you could then simply generate a UUID and use it. This makes it unique inside the client and you are able to bind n servers.

Proposal:

  • Advertise the commands with a suffix that is unique per process, e.g. rescript/openCompiled:<uuid>, and use those IDs in the code actions. Since these commands are only triggered from code actions, no client depends on the exact name.
  • Keep accepting the plain names (rescript/dumpServerState, rescript/dumpCmt, …) in the workspace/executeCommand handler, without advertising them, so clients can still call them directly, e.g. from a command palette.

On the VS Code side this lets us drop a workaround that patches vscode-languageclient's internals, and calls go automatically to the server that produced the code action. Neovim and Zed should be unaffected, since they execute whatever ID the code action carries.

@fhammerschmidt

Copy link
Copy Markdown
Member

Tested the pkg.pr.new build at 00aaba1 from VS Code: rescript lsp exits with "unknown option --clientProcessId". vscode-languageclient always appends --stdio --clientProcessId=<pid> when it starts a Node-based server, and the LSP spec lists it as a standard argument. Could the server accept it (ignoring it is enough)? With that, hover and diagnostics work in our end-to-end tests.

@aspeddro

aspeddro commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor Author

Tested the pkg.pr.new build at 00aaba1 from VS Code: rescript lsp exits with "unknown option --clientProcessId". vscode-languageclient always appends --stdio --clientProcessId=<pid> when it starts a Node-based server, and the LSP spec lists it as a standard argument. Could the server accept it (ignoring it is enough)? With that, hover and diagnostics work in our end-to-end tests.

@fhammerschmidt Yes, I added in cd7dbf8 (Just wait for the CI)

@fhammerschmidt

Copy link
Copy Markdown
Member

On Windows, open files lose their compiler errors. We hit this in the end-to-end tests of the new VS Code extension, running against this PR's build (cd7dbf8).

Cause: the drive letter's case. .compiler.log has the path as the build saw it, for example D:\a\…\src\Broken.res. VS Code sends the same file as file:///d%3A/a/…/src/Broken.res. Compiler log paths become URIs with Uri.of_path (lsp/src/diagnostics.ml, the Full_path p -> Uri.of_path p branch), which keeps D:. The client's URI has d:. In the lsp library, Uri.to_string lowercases the drive letter, but Uri.compare is Stdlib.compare on the stored path (uri0.ml). So the diagnostics map and the document store hold two keys for the same file.

What the client sees after opening Broken.res (trace from the extension, shortened):

Sending notification 'textDocument/didOpen'        uri: file:///d%3A/…/src/Broken.res
Sending request 'textDocument/diagnostic - (6)'
Received notification 'textDocument/publishDiagnostics'   Broken.res: [This has type: string …]   <- the D: entry, treated as a closed file
Received notification 'textDocument/publishDiagnostics'   Broken.res: []                          <- force_publish for the open d: entry
Received response 'textDocument/diagnostic - (6)'          {"kind": "full", "items": []}

The error ends up neither pushed nor pulled. Windows terminals almost always use an uppercase drive (C:\) while VS Code uses lowercase, so most Windows users would hit this. A possible fix is to normalize the drive letter when building URIs from compiler log paths (or relative ones joined to the root), or to key the maps by a normalized URI.

A smaller related point: open documents are left to pull diagnostics, but vscode-languageclient only pulls for documents visible in an editor. A document that is open without an editor (for example opened by another extension) therefore gets no diagnostics at all. That may well be acceptable, but it's how our tests first lost diagnostics.

Ship the language server with the compiler so editor analysis uses the
matching compiler metadata instead of a separately versioned executable.
Consolidate the initial implementation, tests, documentation, and build
integration while retaining the upstream master history.

Command added (language-server entrypoint):
Before (text):
    rescript: build, watch, clean, format, compiler-args
After (text):
    rescript: build, watch, clean, format, compiler-args, lsp --stdio
    The lsp subcommand runs the OCaml server over stdio using Eio.

Connect LSP requests to the in-tree analysis library. Track editor syntax
and compiler diagnostics separately, refresh analysis after builds, and
provide configuration, navigation, interface creation, and debug commands.

Add cross-platform stdio expect tests, editor setup documentation, CI
integration, and third-party license notices for the linked dependencies.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
aspeddro added a commit to aspeddro/rescript-compiler that referenced this pull request Nov 23, 2026
…cript

- Projects can initialize in the same VS Code window. Plain command names remain
  supported for direct client calls.

Fix bug reported in rescript-lang#8425 (comment)

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Accept the positive client PID that some editors append automatically so
their standard launch command works. Keep --stdio mandatory and leave
process monitoring outside this compatibility option.

Command modified (LSP client compatibility):
Before (text):
    rescript lsp --stdio --clientProcessId 123: rejected
After (text):
    rescript lsp --stdio --clientProcessId 123: accepted
    The PID must be a positive integer and is not monitored.

Update CLI parsing tests and help snapshots for the optional argument.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Why:
    A malformed message or handler exception could terminate the server,
    interrupting unrelated editor requests.

Protocol modified (message error recovery):
Before (text):
    Malformed input: terminate the server.
    Request exception: terminate the server.
    Notification exception: terminate the server.
After (text):
    Malformed input: skip it and continue reading.
    Request exception: return a JSON-RPC error and retain session state.
    Notification exception: log to stderr and continue reading.

Diagnostic modified (document store):
Before (diagnostic):
    InvalidRequest: Document store not found <uri> to get
After (diagnostic):
    RequestFailed: Cannot get document <uri>: it is not open.

Add end-to-end snapshots for error recovery, state preservation, and
clean shutdown. Capture subprocess stderr and preserve actual exit codes.

Verified with dune runtest and make dead-code.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Request parameter decoding failures describe invalid client input, not
internal server failures. Return the appropriate JSON-RPC error code and
update the protocol regression snapshot, retaining the initialized state.

Protocol modified (invalid request parameters):
Before (text):
    Invalid hover parameters -> InternalError (-32603)
After (text):
    Invalid hover parameters -> InvalidParams (-32602)

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Why:
    Reading an entire body through the 1 MiB input buffer rejected
    large documents and left the server unable to process later messages.

Protocol modified (message body reads):
Before (text):
    Read the entire Content-Length body in one buffered operation.
    Bodies larger than 1 MiB exceed the reader limit.
After (text):
    Keep direct reads for bodies up to 1 MiB.
    Assemble larger bodies from chunks no larger than 1 MiB.
    Consume exactly Content-Length bytes, preserving the next header.

Add regression tests for opening and editing documents over 2 MiB,
including subsequent requests to verify message framing remains intact.

Verified with dune runtest, make dead-code, and changelog validation.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
… interface

Advertise its command, and refuse to overwrite existing interface files

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
…executable

- Leave documents with syntax errors unchanged without error popups.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Normalize the language-server library's dependency list to Dune's compact
formatting. This changes no dependencies or build behavior.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
…cript

- Projects can initialize in the same VS Code window. Plain command names remain
  supported for direct client calls.

Fix bug reported in rescript-lang#8425 (comment)

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Why:
    Compiler logs and editors can use different drive-letter casing.
    Structural URI comparison treats these as separate documents,
    causing compiler errors to disappear when a file opens.

Representation modified (document and diagnostic keys):
Before (text):
    D:/project/Broken.res and d:/project/Broken.res use separate keys.
    Pull diagnostics for the open document return an empty list.
After (text):
    Serialized URI keys identify both paths as the same document.
    Pull diagnostics retain compiler errors.
    Filename case remains distinct.

Add unit and end-to-end regressions for URI lookup, diagnostic merging,
open/close ownership, and clearing errors after a clean build.
Document the unchanged pull behavior for documents without an editor.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Why:
    The LSP maintained a separate rescript.json decoder whose defaults
    and namespace rules could diverge from the build system.

Representation modified (project configuration):
Before (text):
    The LSP decodes its own partial schema and computes artifact paths.
    Missing package-specs defaults to CommonJS out-of-source output.
After (text):
    Config.of_string decodes Eio-loaded contents using the build schema.
    Rewatch helpers resolve namespaces and generated artifact paths.
    Missing package-specs uses the build's ES module in-source default.

Keep ppx_deriving_yojson for editor settings and decode source-directory
metadata with Yojson directly. Update documentation and license scopes.

Add tests for decoder parity, output defaults, multiple outputs,
namespaces, settings validation, and malformed source-directory metadata.

Signed-off-by: Pedro Castro <aspeddro@gmail.com>
Keep ppx_expect and its transitive runtimes out of the shipped rescript
binary by moving all 13 inline tests to tests/lsp_unit_tests.

Extract rescript_language_server_core so tests exercise the production
implementation while preserving the existing listen interface. Run both
LSP suites through make test-lsp and update the documentation.

Remove the unlinked test dependencies from the license inventory and
regenerate the third-party notices

Signed-off-by: Pedro Castro <aspeddro@gmail.com>

This branch has not been deployed

No deployments
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.

3 participants