Skip to content

Commit adeed7f

Browse files
committed
fix(code-intelligence): give rust-analyzer the standard library through links
In a workspace from cstudy init, rust/.cargo/config.toml replaces crates.io with the runtime's vendored crates. Cargo applies that to the standard library's own workspace too, which rust-analyzer loads with cargo metadata, so std's dependencies were not found and Vec or len resolved to nothing: no hover, definition or completion into the standard library. rust-analyzer 1.92.0 has no setting that skips that query, but it reads the library's crates directly from a directory without a Cargo.toml. Before a Rust session starts, cstudy runs rustc --print sysroot in the root and links each entry of the toolchain's library sources but the manifest and lock into .cs/lsp/rust-library/<root>/, then gives that directory to rust-analyzer alone as cargo.sysrootSrc. rust/.cargo/config.toml and the builds of cstudy test stay as they are. The real rust-analyzer test now runs on a crate with the template's vendoring config, which failed before.
1 parent ba4d94d commit adeed7f

13 files changed

Lines changed: 365 additions & 17 deletions

File tree

‎cli/src/coding_study/application/code_intelligence.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ def directory(self) -> Path:
105105
def lsp_directory(self) -> Path:
106106
return self.workspace / LSP_DIRECTORY
107107

108+
@property
109+
def standard_library_links(self) -> Path | None:
110+
"""Where the links to the standard library the server reads are, for the root; None for
111+
a server that finds the library itself."""
112+
library = self.server.standard_library
113+
return None if library is None else self.lsp_directory / library.links / self.root
114+
108115
@property
109116
def hidden(self) -> tuple[Path, ...]:
110117
"""Where the reference solutions, the generated cases with their expected values, the run

‎cli/src/coding_study/domain/code_intelligence.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,36 @@ def environment(self, lsp_directory: str) -> dict[str, str]:
106106
}
107107

108108

109+
@dataclass(frozen=True, slots=True)
110+
class StandardLibrary:
111+
"""A standard library a server reads from links cstudy makes, in `.cs/lsp/<links>/<root>/`:
112+
one to each entry of the toolchain's library sources but its Cargo manifest and lock.
113+
rust-analyzer runs `cargo metadata` on the library's own Cargo workspace when it has a
114+
manifest, and cargo applies the workspace's `.cargo/config.toml` to that query too: the
115+
vendored crates.io holds none of `std`'s dependencies, so the query fails and `Vec` or `len`
116+
resolve to nothing. Without a manifest, rust-analyzer reads the library's crates directly."""
117+
118+
section: str
119+
"""The settings section where the links go, as `cargo.sysrootSrc`."""
120+
links: str = "rust-library"
121+
"""Under `.cs/lsp/`, then the session's root."""
122+
sysroot_command: tuple[str, ...] = ("rustc", "--print", "sysroot")
123+
"""Prints the sysroot of the toolchain the root selects, run in the root."""
124+
library: str = "lib/rustlib/src/rust/library"
125+
"""The library sources, relative to the sysroot: rustup's `rust-src` component."""
126+
left_out: frozenset[str] = frozenset({"Cargo.toml", "Cargo.lock"})
127+
128+
def settings(self, settings: Mapping[str, JsonValue], directory: str) -> dict[str, JsonValue]:
129+
"""`settings` with the links in `directory` as `cargo.sysrootSrc` of the section."""
130+
section = _fields(settings.get(self.section))
131+
cargo = {**_fields(section.get("cargo")), "sysrootSrc": directory}
132+
return {**settings, self.section: {**section, "cargo": cargo}}
133+
134+
135+
def _fields(value: JsonValue | None) -> dict[str, JsonValue]:
136+
return dict(value) if isinstance(value, dict) else {}
137+
138+
109139
GO_RELEASE_COMMAND = ("go", "env", "GOVERSION")
110140
"""Prints the selected Go's release, `go1.27.3`."""
111141

@@ -180,6 +210,8 @@ class LanguageServer:
180210
missing_words: str | None = None
181211
"""Words a failing version command prints when only a proxy of the server is there, such as
182212
the rustup proxy of a component that is not installed."""
213+
standard_library: StandardLibrary | None = None
214+
"""Set for a server that reads the standard library from links cstudy makes."""
183215

184216
def command(self, launch: Launch) -> tuple[str, ...]:
185217
return self.launcher(self, launch)
@@ -513,6 +545,7 @@ def _rust_analyzer_environment(_launch: Launch) -> dict[str, str]:
513545
versioner=_rust_analyzer_version_command,
514546
fix=f"rustup component add {RUST_ANALYZER_NAME}",
515547
missing_words="Unknown binary",
548+
standard_library=StandardLibrary(section=RUST_ANALYZER_NAME),
516549
)
517550
"""rust-analyzer (ADR 0018, phase 3): the one rustup installs, or any on PATH whose `--version`
518551
runs. cstudy never changes the Rust toolchain. While the component is missing, rustup's proxy on

‎cli/src/coding_study/entrypoints/web/code_intelligence.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
ServerStartError,
3939
environment_hiding,
4040
prepare_data_directory,
41+
prepare_standard_library,
4142
)
4243
from coding_study.entrypoints.web.notifications import Notifications
4344

@@ -326,6 +327,13 @@ async def _start(self, target: SessionTarget, launch: Launch) -> ServerProcess:
326327
await asyncio.to_thread(prepare_data_directory, server, launch)
327328
except OSError as error:
328329
raise ServerStartError(f"cannot write {launch.data_directory}: {error}") from None
330+
try:
331+
await asyncio.to_thread(prepare_standard_library, target, environment)
332+
except OSError as error:
333+
links = target.standard_library_links
334+
raise ServerStartError(
335+
f"cannot link the standard library in {links}: {error}"
336+
) from None
329337
arguments = self.command.arguments(server, launch)
330338
return await ServerProcess.start(arguments, target.directory, self.timing, environment)
331339

‎cli/src/coding_study/entrypoints/web/language_broker.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import asyncio
1616
import json
1717
import re
18+
from collections.abc import Mapping
1819
from dataclasses import dataclass
1920
from pathlib import Path, PurePosixPath
2021
from typing import Any, cast
@@ -215,7 +216,7 @@ def _initialize(self, request_id: Id) -> Delivery:
215216
"rootUri": self._root_uri,
216217
"workspaceFolders": [self._folder()],
217218
"clientInfo": {"name": CLIENT_NAME, "version": self._version},
218-
"initializationOptions": server.initialization_options(str(self._target.workspace)),
219+
"initializationOptions": self._initialization_options(),
219220
"capabilities": server.capabilities,
220221
}
221222
return Delivery(to_server=(_request(request_id, INITIALIZE, params),))
@@ -298,9 +299,30 @@ def _server_request(self, message: Fields, method: str) -> Delivery:
298299
)
299300
return Delivery(to_server=(_response(request_id, result),))
300301

302+
def _initialization_options(self) -> dict[str, Any]:
303+
"""The catalog's, with the standard library the session linked for a server that reads
304+
it from links."""
305+
server = self._target.server
306+
options = server.initialization_options(str(self._target.workspace))
307+
library, links = server.standard_library, self._linked_library()
308+
if library is None or links is None:
309+
return options
310+
return _fields(library.settings({library.section: options}, links)[library.section])
311+
301312
def _setting(self, item: object) -> object:
302313
section = _fields(item).get("section")
303-
return self._target.server.settings.get(section) if isinstance(section, str) else None
314+
return self._settings().get(section) if isinstance(section, str) else None
315+
316+
def _settings(self) -> Mapping[str, Any]:
317+
settings = self._target.server.settings
318+
library, links = self._target.server.standard_library, self._linked_library()
319+
return settings if library is None or links is None else library.settings(settings, links)
320+
321+
def _linked_library(self) -> str | None:
322+
"""The links to the standard library once the session made them; None before, or for
323+
a server that finds the library itself."""
324+
links = self._target.standard_library_links
325+
return str(links) if links is not None and links.is_dir() else None
304326

305327
def _track_registrations(self, method: str, params: Fields) -> None:
306328
registering = method == "client/registerCapability"

‎cli/src/coding_study/entrypoints/web/language_server.py‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,15 @@
77
input closed, then SIGTERM and SIGKILL to the group, as a cancelled run escalates; whatever the
88
server does not read, the stop reaches SIGTERM and SIGKILL on time. A Node server also starts with
99
`hide_paths.cjs` preloaded, which keeps the hidden directories from it
10-
(docs/specs/web-ui.md#hidden-directories).
10+
(docs/specs/web-ui.md#hidden-directories), and rust-analyzer finds the standard library in links
11+
cstudy makes (docs/specs/web-ui.md#language-servers).
1112
"""
1213

1314
import asyncio
1415
import json
1516
import os
1617
import signal
18+
import subprocess
1719
from collections import deque
1820
from collections.abc import Mapping, Sequence
1921
from contextlib import suppress
@@ -22,7 +24,8 @@
2224
from typing import cast
2325

2426
from coding_study.adapters.process_environment import inherited_environment
25-
from coding_study.domain.code_intelligence import LanguageServer, Launch
27+
from coding_study.application.code_intelligence import SessionTarget
28+
from coding_study.domain.code_intelligence import LanguageServer, Launch, StandardLibrary
2629
from coding_study.entrypoints.web.children import StreamedChild, start_process
2730
from coding_study.entrypoints.web.runs import SIGNAL_EXIT_BASE
2831

@@ -42,6 +45,8 @@
4245
GROUP_POLL_S = 0.02
4346
KILL_WAIT_S = 2.0
4447
"""How long a group that got SIGKILL has to disappear before the stop gives up on it."""
48+
SYSROOT_TIMEOUT_S = 30.0
49+
"""How long `rustc --print sysroot` may take: rustup may first read the toolchain files."""
4550

4651

4752
@dataclass(frozen=True, slots=True)
@@ -83,6 +88,59 @@ def prepare_data_directory(server: LanguageServer, launch: Launch) -> None:
8388
path.write_text(content, encoding="utf-8")
8489

8590

91+
def prepare_standard_library(target: SessionTarget, environment: Mapping[str, str]) -> None:
92+
"""Links the standard library of the toolchain the session's root selects (`rustc --print
93+
sysroot`, run in the root, in `environment`) for a server that reads it from links. Nothing
94+
is linked without `rustc` or the toolchain's library sources: the server then looks for the
95+
library itself."""
96+
library = target.server.standard_library
97+
links = target.standard_library_links
98+
if library is None or links is None:
99+
return
100+
sysroot = _sysroot(library, target.directory, environment)
101+
source = None if sysroot is None else sysroot / library.library
102+
if source is not None and source.is_dir():
103+
link_standard_library(library, source, links)
104+
105+
106+
def link_standard_library(library: StandardLibrary, source: Path, links: Path) -> None:
107+
"""`links` holds a link to each entry of `source` but those `library` leaves out, its Cargo
108+
manifest and lock. A link to another toolchain's entry is replaced, each in one rename, so a
109+
session already running on the links never finds one missing; a link to an entry `source`
110+
no longer has is removed."""
111+
links.mkdir(parents=True, exist_ok=True)
112+
wanted = {entry.name: entry for entry in source.iterdir() if entry.name not in library.left_out}
113+
for name, entry in wanted.items():
114+
link = links / name
115+
if link.is_symlink() and link.readlink() == entry:
116+
continue
117+
fresh = links / f".{name}.{os.getpid()}"
118+
fresh.unlink(missing_ok=True)
119+
fresh.symlink_to(entry, target_is_directory=entry.is_dir())
120+
fresh.replace(link)
121+
for link in links.iterdir():
122+
if link.is_symlink() and link.name not in wanted:
123+
link.unlink()
124+
125+
126+
def _sysroot(
127+
library: StandardLibrary, directory: Path, environment: Mapping[str, str]
128+
) -> Path | None:
129+
try:
130+
printed = subprocess.run(
131+
library.sysroot_command,
132+
cwd=directory,
133+
env=dict(environment),
134+
capture_output=True,
135+
text=True,
136+
timeout=SYSROOT_TIMEOUT_S,
137+
check=True,
138+
).stdout.strip()
139+
except (OSError, subprocess.SubprocessError):
140+
return None
141+
return Path(printed) if printed else None
142+
143+
86144
class ServerStartError(Exception):
87145
"""The server could not be started; the text is why, as the 4002 reason says it."""
88146

‎cli/tests/application/test_code_intelligence_session.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,15 @@ def test_a_rust_attempt_gets_rust_analyzer_rooted_in_the_rust_project(practice):
171171
assert (found.server.name, found.root) == ("rust-analyzer", "rust")
172172

173173

174+
def test_a_rust_session_reads_the_standard_library_from_links_of_its_root(practice):
175+
found = target(practice, started(practice, Language.RUST))
176+
assert found.standard_library_links == practice.root / ".cs/lsp/rust-library/rust"
177+
178+
179+
def test_a_session_of_another_server_has_no_links_to_a_standard_library(practice):
180+
assert target(practice, started(practice, Language.GO)).standard_library_links is None
181+
182+
174183
def test_a_rust_attempt_without_rust_analyzer_is_refused_with_the_rustup_fix(tmp_path):
175184
probes = {name: probe for name, probe in INSTALLED_SERVERS.items() if name != "rust-analyzer"}
176185
environment = make_environment(

‎cli/tests/domain/test_code_intelligence.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,57 @@ def test_cargo_runs_offline_under_rust_analyzer():
466466
assert RUST_ANALYZER.environment(NODE_LAUNCH) == {"CARGO_NET_OFFLINE": "true"}
467467

468468

469+
STANDARD_LIBRARY = RUST_ANALYZER.standard_library
470+
LINKS = "/ws/.cs/lsp/rust-library/rust"
471+
472+
473+
def test_rust_analyzer_reads_the_standard_library_from_links_in_the_lsp_directory():
474+
"""The workspace's vendored crates.io reaches `cargo metadata` of the toolchain's library, so
475+
rust-analyzer reads the library's crates from links, without the library's manifest."""
476+
assert STANDARD_LIBRARY is not None
477+
assert (STANDARD_LIBRARY.links, STANDARD_LIBRARY.left_out) == (
478+
"rust-library",
479+
frozenset({"Cargo.toml", "Cargo.lock"}),
480+
)
481+
482+
483+
def test_the_standard_library_is_the_rust_src_of_the_sysroot_rustc_prints():
484+
assert STANDARD_LIBRARY is not None
485+
assert (STANDARD_LIBRARY.sysroot_command, STANDARD_LIBRARY.library) == (
486+
("rustc", "--print", "sysroot"),
487+
"lib/rustlib/src/rust/library",
488+
)
489+
490+
491+
def test_the_links_are_rust_analyzers_sysroot_source_beside_its_other_settings():
492+
assert STANDARD_LIBRARY is not None
493+
assert STANDARD_LIBRARY.settings(RUST_ANALYZER.settings, LINKS) == {
494+
"rust-analyzer": {
495+
"cargo": {"targetDir": True, "sysrootSrc": LINKS},
496+
"check": {"allTargets": True},
497+
"completion": {"autoimport": {"enable": False}},
498+
}
499+
}
500+
501+
502+
def test_the_links_leave_the_catalogs_settings_as_they_were():
503+
assert STANDARD_LIBRARY is not None
504+
STANDARD_LIBRARY.settings(RUST_ANALYZER.settings, LINKS)
505+
assert RUST_ANALYZER.settings == {
506+
"rust-analyzer": {
507+
"cargo": {"targetDir": True},
508+
"check": {"allTargets": True},
509+
"completion": {"autoimport": {"enable": False}},
510+
}
511+
}
512+
513+
514+
def test_only_rust_analyzer_reads_the_standard_library_from_links():
515+
assert [server.name for server in LANGUAGE_SERVERS if server.standard_library] == [
516+
"rust-analyzer"
517+
]
518+
519+
469520
def test_go_and_rust_get_the_same_client_capabilities_as_the_other_servers():
470521
assert (GOPLS.capabilities, RUST_ANALYZER.capabilities) == (
471522
BASEDPYRIGHT.capabilities,

‎cli/tests/entrypoints/web/test_language_broker.py‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1274,6 +1274,37 @@ def test_go_and_rust_servers_get_their_settings_on_request(server, section):
12741274
assert reply["result"] == [server.settings[section]]
12751275

12761276

1277+
def rust_analyzer_with_links(workspace: Path) -> tuple[LanguageBroker, str]:
1278+
"""A rust-analyzer broker whose session linked the standard library; the links."""
1279+
links = workspace / ".cs/lsp/rust-library/rust"
1280+
links.mkdir(parents=True)
1281+
return broker_for(RUST_ANALYZER, "rust", workspace), str(links)
1282+
1283+
1284+
def test_rust_analyzer_is_initialized_with_the_standard_library_its_session_linked(tmp_path):
1285+
broker, links = rust_analyzer_with_links(tmp_path)
1286+
(sent,) = from_page(broker, request(1, "initialize", {})).to_server
1287+
assert sent["params"]["initializationOptions"]["cargo"] == {
1288+
"targetDir": True,
1289+
"sysrootSrc": links,
1290+
}
1291+
1292+
1293+
def test_rust_analyzer_gets_the_linked_standard_library_on_request_too(tmp_path):
1294+
"""Its answer to `workspace/configuration` replaces the initialization options."""
1295+
broker, links = rust_analyzer_with_links(tmp_path)
1296+
items = {"items": [{"section": "rust-analyzer"}]}
1297+
(reply,) = from_server(broker, request("s1", "workspace/configuration", items)).to_server
1298+
assert reply["result"][0]["cargo"]["sysrootSrc"] == links
1299+
1300+
1301+
def test_another_section_gets_no_standard_library(tmp_path):
1302+
broker, _links = rust_analyzer_with_links(tmp_path)
1303+
items = {"items": [{"section": "files"}]}
1304+
(reply,) = from_server(broker, request("s1", "workspace/configuration", items)).to_server
1305+
assert reply["result"] == [None]
1306+
1307+
12771308
def test_a_definition_answer_is_still_forwarded_unchanged(broker):
12781309
page_asks(broker, 20, "textDocument/definition")
12791310
result = [{"uri": "file:///lib/x.pyi", "range": {"start": {"line": 3, "character": 0}}}]

0 commit comments

Comments
 (0)