M3.5: go to definition, find references and rename through Phpactor

Engine (`cmd/lsp_nav.rs`, on the pending outcomes of 20d1d28):
- `lsp.definition` (F12) and `lsp.references` (Shift+F12, sorted, with
  line previews) return project-relative locations; locations outside
  the project, such as PHAR stubs and symlink escapes, are dropped.
- `lsp.prepareRename` uses the word at the cursor when the server has
  no prepareProvider.
- `lsp.rename` (F2) applies the workspace edit (`lsp_nav/edit.rs`):
  1. Check everything first: inside the project, ranges fit (UTF-16,
     CRLF), open buffers unchanged since the request, no file
     operations, no incomplete edit.
  2. Write closed files atomically through the VFS, restoring earlier
     writes when a later one fails.
  3. Change open buffers through `buffer.edit` (dirty, undoable).
  4. Send each written file to Phpactor as didOpen/didSave/didClose
     plus didChangeWatchedFiles; without this its index kept the old
     names. Then the summary notification `notification.lsp.renamed`.

UI (`components/editor/nav/`):
- Mod+click goes to the definition, with a pointer cursor while Mod is
  held.
- A location picker for several definitions (exclusive modal).
- A References tab in the bottom panel, grouped by file.
- An inline rename field with a use/file count (exclusive modal).
- `BufferSync.beginUndoableRemote` puts the engine's rename edit into
  the editor history as one undo step per buffer.
- Catalog strings and tokens only.

Fake LSP server: `--script FILE` with scripted capabilities and
answers (additive next to M3.4's arms).

Tests:
- `crates/engine/tests/lsp_nav.rs` (fake): definition; bad positions;
  references; prepareRename; a multi-file rename incl. a closed CRLF
  file; refusals for outside the project, a bad range, a stale buffer,
  bad names and no server.
- The ignored real-Phpactor test covers definition, references and a
  rename and back across 3 files.
- Vitest `ui/tests/nav/`.

Live (Phpactor 2026.06.25.0, Windows, port 7935, tick on):
- definition 93 ms cold / 7-18 ms warm
- references ~140 ms
- prepareRename ~11 ms
- rename 28-59 ms
- index follows written files in 140 ms
- Phpactor 57 MB working set, ~1.6% of a core while ticking idle

Gate: 13 steps, 197 s, Vitest 484 + 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-22 18:50:15 +02:00
parent b3fd7c6478
commit 578160a2ba
28 changed files with 3730 additions and 34 deletions

View file

@ -0,0 +1,839 @@
//! Navigation and refactoring through the language server (M3.5):
//! `lsp.definition`, `lsp.references`, `lsp.prepareRename` and
//! `lsp.rename`.
//!
//! Every command names an open buffer and a position in it (0-based line,
//! UTF-16 column). The request goes to the server through
//! [`crate::lsp::submit`], after every document change queued so far, so the
//! server answers for the text the user sees. The engine lock is never held
//! while the server works: the command returns a [`crate::Pending`] that the
//! host waits for without the lock, and the answer is turned into the result
//! under the lock again ([`crate::Engine::resolve`]).
//!
//! Results:
//! - Locations are project-relative; locations outside the project (PHP
//! stubs inside the Phpactor PHAR, files elsewhere on disk) are left out,
//! because Lutra only opens project files.
//! - `lsp.rename` applies the workspace edit as [`edit`] describes and
//! reports it with one summary notification.
pub mod edit;
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::sync::mpsc;
use std::time::Duration;
use lutra_lsp::{Location, LspError, Server, WorkspaceEdit};
use lutra_text::{Buffer, Position};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::params::parse;
use crate::buffers::BufferId;
use crate::lsp::{LinePosition, LineRange};
use crate::workspace::path_string;
use crate::{
Command, CommandSpec, EngineError, NotificationLevel, Outcome, Pending, Registry, State,
};
/// How long a navigation request may take before it fails with a timeout.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
/// How long a rename may take: Phpactor searches the whole project.
pub const RENAME_TIMEOUT: Duration = Duration::from_secs(30);
/// Most locations returned by `lsp.definition` and `lsp.references`.
pub const MAX_LOCATIONS: usize = 10_000;
/// Longest new name `lsp.rename` accepts, in bytes.
pub const MAX_NAME_BYTES: usize = 1_024;
/// Registers the commands of this module.
///
/// # Errors
/// [`EngineError::Internal`] if an id is already taken.
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(Definition))?;
registry.register(Box::new(References))?;
registry.register(Box::new(PrepareRename))?;
registry.register(Box::new(Rename))?;
Ok(())
}
/// A position in a buffer, as clients send it.
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(deny_unknown_fields)]
struct PositionParam {
/// 0-based line.
line: usize,
/// 0-based column in UTF-16 code units.
column: usize,
}
/// Params of `lsp.definition` and `lsp.prepareRename`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct AtParams {
/// Buffer id.
id: BufferId,
/// Where the cursor is.
position: PositionParam,
}
/// Params of `lsp.references`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct ReferencesParams {
/// Buffer id.
id: BufferId,
/// Where the cursor is.
position: PositionParam,
/// Include the declaration itself (default true).
#[serde(default = "yes")]
include_declaration: bool,
}
/// `true`, for serde defaults.
fn yes() -> bool {
true
}
/// Params of `lsp.rename`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct RenameParams {
/// Buffer id.
id: BufferId,
/// Where the symbol is.
position: PositionParam,
/// The new name.
new_name: String,
}
/// A location in a project file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NavLocation {
/// Project-relative path with `/`.
pub path: String,
/// The range.
pub range: LineRange,
}
/// What a request needs from the state: the server-side path of the buffer,
/// the checked position and the project root.
struct Target {
/// Absolute path of the buffer's file.
abs: PathBuf,
/// The position.
position: Position,
/// The project root.
root: PathBuf,
}
/// Resolves buffer `id` and checks `position` against its text.
///
/// # Errors
/// [`EngineError::Failed`] for an unknown buffer, a position outside the
/// text, or no running language server; [`EngineError::InvalidParams`]
/// never (the shape was parsed already).
fn target(
state: &State,
command: &str,
id: BufferId,
position: PositionParam,
) -> Result<Target, EngineError> {
let open = state
.buffers
.get(id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {id}")))?;
let position = Position {
line: position.line,
column: position.column,
};
open.buffer
.position_to_offset(position, lutra_text::ColumnUnit::Utf16)
.map_err(|e| EngineError::invalid_params(command, e.to_string()))?;
let root = state
.project
.as_ref()
.ok_or_else(|| EngineError::Disabled(command.to_string()))?
.project
.root()
.to_path_buf();
if state.lsp.server().is_none() {
return Err(EngineError::Failed(
"the PHP language server is not running".into(),
));
}
Ok(Target {
abs: root.join(&open.path),
position,
root,
})
}
/// Sends a request built by `send` on the session thread, after every
/// queued document change, and returns a receiver for the answer. The
/// session's document sync runs first, so a buffer opened a moment ago is
/// known to the server.
///
/// # Errors
/// [`EngineError::Failed`] when no session runs.
fn request(
state: &mut State,
method: &'static str,
params: Value,
timeout: Duration,
) -> Result<mpsc::Receiver<Result<Value, LspError>>, EngineError> {
crate::lsp::pump(state);
let (tx, rx) = mpsc::channel();
let queued = crate::lsp::submit(state, move |server: &Server| {
let reply = tx.clone();
let sent = server.request_with(
method,
params,
timeout,
Box::new(move |result| {
let _ = reply.send(result);
}),
);
if let Err(e) = sent {
let _ = tx.send(Err(e));
}
});
if !queued {
return Err(EngineError::Failed(
"the PHP language server is not running".into(),
));
}
Ok(rx)
}
/// `{textDocument: {uri}, position: {line, character}}` for `target`.
///
/// # Errors
/// [`EngineError::Failed`] if the path has no `file:` URI.
fn document_position(target: &Target) -> Result<Map<String, Value>, EngineError> {
let uri = lutra_lsp::uri::path_to_uri(&target.abs).map_err(|e| {
EngineError::Failed(format!("cannot address {}: {e}", target.abs.display()))
})?;
let mut params = Map::new();
params.insert("textDocument".into(), json!({ "uri": uri }));
params.insert(
"position".into(),
json!({ "line": target.position.line, "character": target.position.column }),
);
Ok(params)
}
/// Turns a server failure into the command's error.
fn server_error(method: &str, error: LspError) -> EngineError {
match error {
LspError::Timeout { .. } => EngineError::Failed(format!(
"the PHP language server did not answer {method} in time"
)),
other => EngineError::Failed(format!("{method} failed: {other}")),
}
}
/// The answer of a pending request, or the error it ended with.
///
/// # Errors
/// [`EngineError::Failed`] for a server error, a timeout, or a session that
/// ended before answering.
fn answer(method: &str, answer: Option<Result<Value, LspError>>) -> Result<Value, EngineError> {
match answer {
Some(Ok(value)) => Ok(value),
Some(Err(e)) => Err(server_error(method, e)),
None => Err(EngineError::Failed(format!(
"the PHP language server stopped before answering {method}"
))),
}
}
/// Project-relative locations from a definition or references result,
/// without duplicates and capped at [`MAX_LOCATIONS`], in the server's
/// order.
pub fn locations(state: &State, root: &Path, value: &Value) -> Vec<NavLocation> {
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for location in Location::list_from_json(value) {
let Some(rel) = location
.path
.as_deref()
.and_then(|p| project_relative(state, root, p))
else {
continue;
};
let item = NavLocation {
path: path_string(&rel),
range: LineRange {
start: LinePosition::from(location.range.start),
end: LinePosition::from(location.range.end),
},
};
let key = (
item.path.clone(),
item.range.start.line,
item.range.start.column,
item.range.end.line,
item.range.end.column,
);
if seen.insert(key) {
out.push(item);
}
if out.len() >= MAX_LOCATIONS {
break;
}
}
out
}
/// `path` (absolute, from the server) relative to the project, or `None`
/// outside it. Windows paths compare without regard to case, as the file
/// system does, and `..` never escapes. A path that resolves through a
/// symbolic link to a place outside the project counts as outside.
pub fn project_relative(state: &State, root: &Path, path: &Path) -> Option<PathBuf> {
let rel = match state
.project
.as_ref()
.and_then(|w| w.project.relative(path))
{
Some(rel) => rel,
None => windows_relative(root, path)?,
};
if rel.components().any(|c| !matches!(c, Component::Normal(_))) {
return None;
}
if let (Ok(real_root), Ok(real)) = (
std::fs::canonicalize(root),
std::fs::canonicalize(root.join(&rel)),
) && !real.starts_with(&real_root)
{
return None;
}
Some(rel)
}
/// The case-insensitive fallback of [`project_relative`] on Windows.
fn windows_relative(root: &Path, path: &Path) -> Option<PathBuf> {
if !cfg!(windows) {
return None;
}
let root_text = root.to_str()?.trim_end_matches(['\\', '/']);
let text = path.to_str()?;
let head = text.get(..root_text.len())?;
let rest = text.get(root_text.len()..)?;
if !head.eq_ignore_ascii_case(root_text) || !rest.starts_with(['\\', '/']) {
return None;
}
Some(PathBuf::from(rest.trim_start_matches(['\\', '/'])))
}
/// `lsp.definition`: where the symbol at a position is declared.
pub struct Definition;
impl Command for Definition {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "lsp.definition",
label: "Go to Definition",
menu_path: Some("Navigate/Go to Definition"),
default_shortcut: Some("F12"),
params: "{ id: buffer id, position: { line, column } (0-based, UTF-16 column) }; returns { locations: [{ path, range: { start: { line, column }, end } }] } (project files only; empty when the server knows no definition); fails when no language server runs",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: AtParams = parse(command, params)?;
let target = target(state, command, p.id, p.position)?;
let params = Value::Object(document_position(&target)?);
let rx = request(state, "textDocument/definition", params, REQUEST_TIMEOUT)?;
let root = target.root;
Ok(Outcome::pending(Pending::new(
rx,
REQUEST_TIMEOUT,
move |state, reply| {
let value = answer("definition", reply)?;
let locations = locations(state, &root, &value);
Ok(json!({ "locations": locations }))
},
)))
}
}
/// `lsp.references`: every use of the symbol at a position.
pub struct References;
impl Command for References {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "lsp.references",
label: "Find References",
menu_path: Some("Navigate/Find References"),
default_shortcut: Some("Shift+F12"),
params: "{ id: buffer id, position: { line, column }, includeDeclaration?: bool (default true) }; returns { locations: [{ path, range, preview, previewColumn }] } sorted by path and position (project files only); preview is the trimmed line text, previewColumn the UTF-16 column of the range start in it",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: ReferencesParams = parse(command, params)?;
let target = target(state, command, p.id, p.position)?;
let mut params = document_position(&target)?;
params.insert(
"context".into(),
json!({ "includeDeclaration": p.include_declaration }),
);
let rx = request(
state,
"textDocument/references",
Value::Object(params),
REQUEST_TIMEOUT,
)?;
let root = target.root;
Ok(Outcome::pending(Pending::new(
rx,
REQUEST_TIMEOUT,
move |state, reply| {
let value = answer("references", reply)?;
let mut found = locations(state, &root, &value);
found.sort_by(|a, b| {
(&a.path, a.range.start.line, a.range.start.column).cmp(&(
&b.path,
b.range.start.line,
b.range.start.column,
))
});
let items = with_previews(state, &root, found);
Ok(json!({ "locations": items }))
},
)))
}
}
/// Most characters of a line kept in a reference preview.
const PREVIEW_CHARS: usize = 200;
/// Adds the line text to each location: from the open buffer if the file is
/// open, otherwise from disk (each file read once). A file that cannot be
/// read gets an empty preview.
fn with_previews(state: &State, root: &Path, found: Vec<NavLocation>) -> Vec<Value> {
let mut texts: BTreeMap<String, Option<Buffer>> = BTreeMap::new();
found
.into_iter()
.map(|location| {
let buffer = texts.entry(location.path.clone()).or_insert_with(|| {
let rel = PathBuf::from(&location.path);
match state
.buffers
.find(&rel)
.and_then(|id| state.buffers.get(id))
{
Some(open) => Some(open.buffer.clone()),
None => lutra_vfs::read_text(&root.join(&rel))
.ok()
.map(|f| Buffer::new(&f.text)),
}
});
let (preview, column) = buffer
.as_ref()
.map(|b| preview(b, location.range.start))
.unwrap_or_default();
json!({
"path": location.path,
"range": location.range,
"preview": preview,
"previewColumn": column,
})
})
.collect()
}
/// The text of `at`'s line without leading whitespace, cut to
/// [`PREVIEW_CHARS`], and `at`'s UTF-16 column in it.
fn preview(buffer: &Buffer, at: LinePosition) -> (String, usize) {
let Ok(line) = buffer.line_text(at.line) else {
return (String::new(), 0);
};
let trimmed = line.trim_start();
let cut = line.len().saturating_sub(trimmed.len());
let removed: usize = line
.get(..cut)
.map(|s| s.encode_utf16().count())
.unwrap_or(0);
let text: String = trimmed.trim_end().chars().take(PREVIEW_CHARS).collect();
(text, at.column.saturating_sub(removed))
}
/// The answer of `lsp.prepareRename`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Renameable {
/// The range of the name that is renamed.
pub range: LineRange,
/// The current name, the suggested start of the new one.
pub placeholder: String,
}
/// The name at `range` in `buffer`, for a server that answered with a
/// range only.
fn name_at(buffer: &Buffer, range: &lutra_lsp::Range) -> Option<String> {
let (start, end) = edit::byte_range(buffer, range).ok()?;
buffer.slice(start..end).ok()
}
/// The identifier around `at` in `buffer` (letters, digits, `_`, a leading
/// `$`, and non-ASCII characters as PHP allows), for servers without
/// `prepareRename`. `None` when the cursor is not on a name.
fn word_at(buffer: &Buffer, at: Position) -> Option<Renameable> {
let line = buffer.line_text(at.line).ok()?;
let units: Vec<(usize, char)> = line
.chars()
.scan(0usize, |cu, c| {
let start = *cu;
*cu += c.len_utf16();
Some((start, c))
})
.collect();
let is_name = |c: char| c.is_alphanumeric() || c == '_' || !c.is_ascii();
let index = units
.iter()
.position(|(cu, c)| *cu + c.len_utf16() > at.column && is_name(*c))
.filter(|&i| units.get(i).is_some_and(|(cu, _)| *cu <= at.column))
.or_else(|| {
units
.iter()
.rposition(|(cu, c)| *cu + c.len_utf16() == at.column && is_name(*c))
})?;
let mut first = index;
while first > 0 && units.get(first - 1).is_some_and(|(_, c)| is_name(*c)) {
first -= 1;
}
if first > 0 && units.get(first - 1).is_some_and(|(_, c)| *c == '$') {
first -= 1;
}
let mut last = index;
while units.get(last + 1).is_some_and(|(_, c)| is_name(*c)) {
last += 1;
}
let (start, _) = *units.get(first)?;
let (end_start, end_char) = *units.get(last)?;
let end = end_start + end_char.len_utf16();
let placeholder: String = units.get(first..=last)?.iter().map(|(_, c)| *c).collect();
if placeholder
.chars()
.next()
.is_some_and(|c| c.is_ascii_digit())
{
return None;
}
Some(Renameable {
range: LineRange {
start: LinePosition {
line: at.line,
column: start,
},
end: LinePosition {
line: at.line,
column: end,
},
},
placeholder,
})
}
/// Reads a `prepareRename` answer: a range, `{range, placeholder}`, or
/// `{defaultBehavior: true}` (then the word at the cursor); `null` means
/// the position cannot be renamed.
fn renameable(buffer: Option<&Buffer>, at: Position, value: &Value) -> Option<Renameable> {
if value.is_null() {
return None;
}
if value.get("defaultBehavior").and_then(Value::as_bool) == Some(true) {
return word_at(buffer?, at);
}
let range_value = value.get("range").unwrap_or(value);
let range = lutra_lsp::Range::from_json(range_value)?;
let placeholder = match value.get("placeholder").and_then(Value::as_str) {
Some(text) => text.to_string(),
None => name_at(buffer?, &range)?,
};
Some(Renameable {
range: LineRange {
start: range.start.into(),
end: range.end.into(),
},
placeholder,
})
}
/// `lsp.prepareRename`: whether the symbol at a position can be renamed,
/// and its current name.
pub struct PrepareRename;
impl Command for PrepareRename {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "lsp.prepareRename",
label: "Prepare Rename",
menu_path: None,
default_shortcut: None,
params: "{ id: buffer id, position: { line, column } }; returns { range, placeholder } for a renameable symbol, or null when the position cannot be renamed; uses the word at the cursor when the server has no prepareRename",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: AtParams = parse(command, params)?;
let target = target(state, command, p.id, p.position)?;
let supports_prepare = state
.lsp
.server()
.and_then(|s| s.capabilities())
.is_some_and(|c| {
c.raw
.get("renameProvider")
.and_then(|r| r.get("prepareProvider"))
.and_then(Value::as_bool)
== Some(true)
});
let id = p.id;
let at = target.position;
if !supports_prepare {
let found = state
.buffers
.get(id)
.and_then(|open| word_at(&open.buffer, at));
return Ok(Outcome::value(
serde_json::to_value(found).map_err(|e| EngineError::Internal(e.to_string()))?,
));
}
let params = Value::Object(document_position(&target)?);
let rx = request(state, "textDocument/prepareRename", params, REQUEST_TIMEOUT)?;
Ok(Outcome::pending(Pending::new(
rx,
REQUEST_TIMEOUT,
move |state, reply| {
let value = match reply {
Some(Err(LspError::Response { .. })) => Value::Null,
other => answer("prepareRename", other)?,
};
let buffer = state.buffers.get(id).map(|o| &o.buffer);
let found = renameable(buffer, at, &value);
serde_json::to_value(found).map_err(|e| EngineError::Internal(e.to_string()))
},
)))
}
}
/// Checks a new name: not empty, one line, at most [`MAX_NAME_BYTES`].
///
/// # Errors
/// [`EngineError::InvalidParams`] naming `command`.
fn check_name(command: &str, name: &str) -> Result<(), EngineError> {
if name.trim().is_empty() {
return Err(EngineError::invalid_params(command, "newName is empty"));
}
if name.contains(['\n', '\r']) {
return Err(EngineError::invalid_params(
command,
"newName must be one line",
));
}
if name.len() > MAX_NAME_BYTES {
return Err(EngineError::invalid_params(
command,
format!("newName is longer than {MAX_NAME_BYTES} bytes"),
));
}
Ok(())
}
/// `lsp.rename`: renames the symbol at a position everywhere in the
/// project.
pub struct Rename;
impl Command for Rename {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "lsp.rename",
label: "Rename Symbol",
menu_path: Some("Refactor/Rename…"),
default_shortcut: Some("F2"),
params: "{ id: buffer id, position: { line, column }, newName }; applies the server's workspace edit: open buffers through buffer.edit (dirty, undoable in the editor), closed files written atomically; refused as a whole when a file is outside the project, an edit does not fit, a buffer changed meanwhile, or the server wants to create/rename/delete files; returns { files: [{ path, edits, bufferId?, version? }], edits, written } and notifies a summary",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: RenameParams = parse(command, params)?;
check_name(command, &p.new_name)?;
let target = target(state, command, p.id, p.position)?;
let mut params = document_position(&target)?;
params.insert("newName".into(), Value::from(p.new_name.clone()));
let versions: BTreeMap<BufferId, u64> = state
.buffers
.ids()
.into_iter()
.filter_map(|id| Some((id, state.buffers.get(id)?.version)))
.collect();
let rx = request(
state,
"textDocument/rename",
Value::Object(params),
RENAME_TIMEOUT,
)?;
let root = target.root;
let new_name = p.new_name;
Ok(Outcome::pending(Pending::new(
rx,
RENAME_TIMEOUT,
move |state, reply| {
let value = answer("rename", reply)?;
if value.is_null() {
return Err(EngineError::Failed(
"the language server found nothing to rename here".into(),
));
}
let edit = WorkspaceEdit::from_json(&value).ok_or_else(|| {
EngineError::Failed("the language server sent no valid edit".into())
})?;
let mut applied = edit::apply(state, &root, &edit, &versions)?;
announce_written(state, std::mem::take(&mut applied.written_files));
notify_summary(state, &new_name, &applied);
serde_json::to_value(&applied).map_err(|e| EngineError::Internal(e.to_string()))
},
)))
}
}
/// Tells the language server that a rename wrote `files` on disk, so its
/// index follows at once: each file is opened with its new text and closed
/// again (`didOpen`, `didSave`, `didClose`), which makes Phpactor reindex it, and
/// `workspace/didChangeWatchedFiles` reports the change for servers that
/// watch through the client. Phpactor ignored the notification alone and
/// kept the old names until its own polling watcher noticed (live check:
/// a "method does not exist" error stayed on the renamed call, and renaming
/// back found one use instead of four). A file the user opened meanwhile is
/// skipped, because its buffer is synced already (`did_open` refuses it).
/// Without a ready session nothing is sent, so the results of `submit`,
/// `did_open`, `did_save`, `did_close` and `notify` are ignored: a session that starts
/// later indexes the files fresh.
fn announce_written(state: &mut State, files: Vec<(PathBuf, String)>) {
if files.is_empty() {
return;
}
let _ = crate::lsp::submit(state, move |server| {
let changes: Vec<Value> = files
.iter()
.filter_map(|(path, _)| lutra_lsp::uri::path_to_uri(path).ok())
.map(|uri| json!({ "uri": uri, "type": 2 }))
.collect();
for (path, text) in &files {
if server.did_open(path, "php", text).is_ok() {
let _ = server.did_save(path);
let _ = server.did_close(path);
}
}
let _ = server.notify(
"workspace/didChangeWatchedFiles",
json!({ "changes": changes }),
);
});
}
/// Tells the user what a rename changed, in one notification.
fn notify_summary(state: &mut State, new_name: &str, applied: &edit::Applied) {
let mut params = Map::new();
params.insert("name".into(), Value::from(new_name));
params.insert("edits".into(), Value::from(applied.edits));
params.insert("files".into(), Value::from(applied.files.len()));
params.insert("written".into(), Value::from(applied.written));
state.notify(
NotificationLevel::Info,
Some("notification.lsp.renamed"),
Some(format!(
"Renamed to {new_name}: {} occurrences in {} files ({} closed files saved).",
applied.edits,
applied.files.len(),
applied.written
)),
Some(params),
);
}
#[cfg(test)]
mod tests {
use super::*;
fn at(line: usize, column: usize) -> Position {
Position { line, column }
}
#[test]
fn finds_the_word_at_the_cursor() {
let buffer = Buffer::new("<?php\n$foo = bar_baz(1);\n");
let w = word_at(&buffer, at(1, 2)).unwrap();
assert_eq!(w.placeholder, "$foo");
assert_eq!((w.range.start.column, w.range.end.column), (0, 4));
let w = word_at(&buffer, at(1, 7)).unwrap();
assert_eq!(w.placeholder, "bar_baz");
let w = word_at(&buffer, at(1, 14)).unwrap();
assert_eq!(w.placeholder, "bar_baz", "cursor right after the name");
assert!(word_at(&buffer, at(1, 16)).is_none(), "a number");
assert!(word_at(&buffer, at(1, 5)).is_none(), "a space");
}
#[test]
fn reads_prepare_rename_answers() {
let buffer = Buffer::new("<?php\nfunction hello() {}\n");
let range =
json!({"start": {"line": 1, "character": 9}, "end": {"line": 1, "character": 14}});
let r = renameable(Some(&buffer), at(1, 10), &range).unwrap();
assert_eq!(r.placeholder, "hello");
let r = renameable(
Some(&buffer),
at(1, 10),
&json!({"range": range, "placeholder": "x"}),
)
.unwrap();
assert_eq!(r.placeholder, "x");
let r = renameable(Some(&buffer), at(1, 10), &json!({"defaultBehavior": true})).unwrap();
assert_eq!(r.placeholder, "hello");
assert!(renameable(Some(&buffer), at(1, 10), &Value::Null).is_none());
}
#[test]
fn previews_trim_the_line() {
let buffer = Buffer::new("<?php\n $a->run();\r\n");
let (text, column) = preview(&buffer, LinePosition { line: 1, column: 8 });
assert_eq!(text, "$a->run();");
assert_eq!(column, 4);
}
#[test]
fn names_are_checked() {
assert!(check_name("x", "ok").is_ok());
assert!(check_name("x", " ").is_err());
assert!(check_name("x", "a\nb").is_err());
assert!(check_name("x", &"a".repeat(MAX_NAME_BYTES + 1)).is_err());
}
}

View file

@ -0,0 +1,322 @@
//! Applying a language server's workspace edit (`lsp.rename`).
//!
//! The edit is checked completely before anything changes:
//! - It must be complete (no skipped edits) and contain text edits only (no
//! file creation, renaming or deletion).
//! - Every document must lie inside the project; one outside refuses the
//! whole edit.
//! - Every edit must apply: ranges are converted with the text crate
//! (UTF-16 columns, CRLF counted as one line break) and tried on a copy.
//! - Open buffers must still be at the version they had when the request was
//! sent; a buffer the user changed meanwhile refuses the edit (the ranges
//! would be stale).
//!
//! Then closed files are written, each atomically through the VFS. If a
//! write fails, the files written so far are restored to their old content
//! (best effort; a failed restore is reported in the error) and no buffer
//! is touched. Only after every file is written are the open buffers changed,
//! through `buffer.edit` (one batch per buffer, so they become dirty and the
//! editor can undo it), which cannot fail any more after the checks.
//! "All or nothing" therefore holds except for a crash or a failed restore
//! between two file writes.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use lutra_lsp::{Range, WorkspaceEdit};
use lutra_text::{Buffer, ColumnUnit, Edit};
use serde::Serialize;
use serde_json::json;
use crate::buffers::BufferId;
use crate::workspace::{path_string, vfs_error};
use crate::{Command, EngineError, State};
/// Most documents one workspace edit may change.
pub const MAX_FILES: usize = 5_000;
/// What happened to one file of an applied edit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileChange {
/// Project-relative path with `/`.
pub path: String,
/// Number of text edits applied.
pub edits: usize,
/// The open buffer that was changed; `None` for a file written on disk.
#[serde(skip_serializing_if = "Option::is_none")]
pub buffer_id: Option<BufferId>,
/// The buffer's version after the edit.
#[serde(skip_serializing_if = "Option::is_none")]
pub version: Option<u64>,
}
/// The summary of an applied workspace edit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct Applied {
/// Changed files, sorted by path.
pub files: Vec<FileChange>,
/// Text edits over all files.
pub edits: usize,
/// Files written on disk (not open).
pub written: usize,
/// The files written on disk, absolute path and new text, for telling
/// the language server.
#[serde(skip)]
pub written_files: Vec<(PathBuf, String)>,
}
/// One document of the edit, checked and ready to apply.
enum Planned {
/// An open buffer: `buffer.edit` with UTF-16 offsets at `base`.
Buffer {
/// The buffer.
id: BufferId,
/// Its current version.
base: u64,
/// `(from, to, insert)` in UTF-16 code units of the current text.
edits: Vec<(usize, usize, String)>,
},
/// A closed file: its old and new contents.
Disk {
/// Absolute path.
abs: PathBuf,
/// The text before the edit, for a restore.
old: String,
/// The text after the edit.
new: String,
/// Whether the file has a byte order mark.
bom: bool,
},
}
/// Applies `edit` to the project. See the module docs.
///
/// # Parameters
/// - `root`: the project root the server was started in (absolute).
/// - `versions`: the versions of the open buffers when the request was
/// sent, by id.
///
/// # Errors
/// [`EngineError::Failed`] with the reason when the edit is refused or a
/// file cannot be written; nothing (or, after a failed restore, only what
/// the message lists) has changed then.
pub fn apply(
state: &mut State,
root: &Path,
edit: &WorkspaceEdit,
versions: &BTreeMap<BufferId, u64>,
) -> Result<Applied, EngineError> {
let plan = plan(state, root, edit, versions)?;
let mut applied = Applied::default();
let mut written: Vec<(PathBuf, &str, bool)> = Vec::new();
for (rel, planned, count) in &plan {
if let Planned::Disk { abs, old, new, bom } = planned {
if let Err(e) = lutra_vfs::write_text(abs, new, *bom) {
let failed = restore(&written);
let mut message = format!("cannot write {}: {}", path_string(rel), vfs_error(e));
if !failed.is_empty() {
message.push_str(&format!(
"; these files keep the new text because restoring them failed too: {}",
failed.join(", ")
));
}
return Err(EngineError::Failed(message));
}
written.push((abs.clone(), old.as_str(), *bom));
applied.written_files.push((abs.clone(), new.clone()));
applied.written = applied.written.saturating_add(1);
applied.files.push(FileChange {
path: path_string(rel),
edits: *count,
buffer_id: None,
version: None,
});
applied.edits = applied.edits.saturating_add(*count);
}
}
for (rel, planned, count) in plan {
if let Planned::Buffer { id, base, edits } = planned {
let changes: Vec<_> = edits
.into_iter()
.map(|(from, to, insert)| json!({"from": from, "to": to, "insert": insert}))
.collect();
let out = super::super::buffer::Edit.run(
state,
json!({"id": id, "baseVersion": base, "edits": changes}),
)?;
applied.files.push(FileChange {
path: path_string(&rel),
edits: count,
buffer_id: Some(id),
version: out.value.get("version").and_then(|v| v.as_u64()),
});
applied.edits = applied.edits.saturating_add(count);
}
}
applied.files.sort_by(|a, b| a.path.cmp(&b.path));
Ok(applied)
}
/// Writes the old contents back into files written by a failed edit.
///
/// # Returns
/// The paths whose restore failed too.
fn restore(written: &[(PathBuf, &str, bool)]) -> Vec<String> {
written
.iter()
.filter(|(abs, old, bom)| lutra_vfs::write_text(abs, old, *bom).is_err())
.map(|(abs, _, _)| abs.display().to_string())
.collect()
}
/// Checks the whole edit and computes every change without applying any.
///
/// # Returns
/// The documents with their project-relative path, change and edit count.
///
/// # Errors
/// [`EngineError::Failed`] naming the first problem.
fn plan(
state: &State,
root: &Path,
edit: &WorkspaceEdit,
versions: &BTreeMap<BufferId, u64>,
) -> Result<Vec<(PathBuf, Planned, usize)>, EngineError> {
if edit.incomplete {
return Err(EngineError::Failed(
"the language server sent an incomplete or malformed edit; nothing was changed".into(),
));
}
if edit.has_resource_operations {
return Err(EngineError::Failed(
"the edit creates, renames or deletes files, which Lutra does not support yet; nothing was changed".into(),
));
}
let mut documents: BTreeMap<PathBuf, Vec<&lutra_lsp::TextEdit>> = BTreeMap::new();
for document in &edit.documents {
let rel = document
.path
.as_deref()
.and_then(|p| super::project_relative(state, root, p))
.ok_or_else(|| {
EngineError::Failed(format!(
"the edit changes {}, which is outside the project; nothing was changed",
document.uri
))
})?;
documents
.entry(rel)
.or_default()
.extend(document.edits.iter());
}
if documents.len() > MAX_FILES {
return Err(EngineError::Failed(format!(
"the edit changes {} files, more than the {MAX_FILES} Lutra applies at once; nothing was changed",
documents.len()
)));
}
let mut plan = Vec::with_capacity(documents.len());
for (rel, edits) in documents {
if edits.is_empty() {
continue;
}
let shown = path_string(&rel);
let count = edits.len();
let planned = match state.buffers.find(&rel) {
Some(id) => {
let open = state
.buffers
.get(id)
.ok_or_else(|| EngineError::Internal(format!("buffer {id} vanished")))?;
let expected = versions.get(&id).copied();
if expected.is_some_and(|v| v != open.version)
|| (expected.is_none() && open.dirty())
{
return Err(EngineError::Failed(format!(
"{shown} changed while the language server computed the edit; nothing was changed, try again"
)));
}
let byte_edits = byte_edits(&open.buffer, &edits, &shown)?;
let mut probe = open.buffer.clone();
probe.apply(&byte_edits).map_err(|e| bad_edit(&shown, &e))?;
let mut utf16 = Vec::with_capacity(byte_edits.len());
for e in byte_edits {
let from = open
.buffer
.offset_to_utf16(e.range.start)
.map_err(|err| bad_edit(&shown, &err))?;
let to = open
.buffer
.offset_to_utf16(e.range.end)
.map_err(|err| bad_edit(&shown, &err))?;
utf16.push((from, to, e.text));
}
Planned::Buffer {
id,
base: open.version,
edits: utf16,
}
}
None => {
let abs = super::super::params::absolute(state, "lsp.rename", &rel)?;
let file = lutra_vfs::read_text(&abs).map_err(|e| {
EngineError::Failed(format!(
"cannot read {shown}: {}; nothing was changed",
vfs_error(e)
))
})?;
let mut buffer = Buffer::new(&file.text);
let byte_edits = byte_edits(&buffer, &edits, &shown)?;
buffer
.apply(&byte_edits)
.map_err(|e| bad_edit(&shown, &e))?;
Planned::Disk {
abs,
new: buffer.text(),
old: file.text,
bom: file.bom,
}
}
};
plan.push((rel, planned, count));
}
Ok(plan)
}
/// Converts LSP text edits (line, UTF-16 column) into byte edits of
/// `buffer`.
///
/// # Errors
/// [`EngineError::Failed`] for a range that does not fit the text.
fn byte_edits(
buffer: &Buffer,
edits: &[&lutra_lsp::TextEdit],
shown: &str,
) -> Result<Vec<Edit>, EngineError> {
edits
.iter()
.map(|e| {
let (start, end) = byte_range(buffer, &e.range).map_err(|err| bad_edit(shown, &err))?;
Ok(Edit::replace(start..end, e.new_text.clone()))
})
.collect()
}
/// The byte range of an LSP range in `buffer`.
///
/// # Errors
/// The text crate's error for a position that does not exist.
pub fn byte_range(buffer: &Buffer, range: &Range) -> Result<(usize, usize), lutra_text::TextError> {
let start = buffer.position_to_offset(range.start, ColumnUnit::Utf16)?;
let end = buffer.position_to_offset(range.end, ColumnUnit::Utf16)?;
Ok((start, end))
}
/// The error for an edit that does not fit `shown`'s text.
fn bad_edit(shown: &str, error: &lutra_text::TextError) -> EngineError {
EngineError::Failed(format!(
"the edit does not fit {shown} ({error}); nothing was changed"
))
}

View file

@ -6,6 +6,7 @@ mod file;
pub mod goto;
mod lsp_assist;
mod lsp_diagnostics;
mod lsp_nav;
mod params;
mod project;
mod recovery;
@ -62,5 +63,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(terminal::Close))?;
lsp_diagnostics::register(registry)?;
lsp_assist::register(registry)?;
lsp_nav::register(registry)?;
Ok(())
}