From 4a2bd1262d821528c613c1fba0eb40a0e16543cc Mon Sep 17 00:00:00 2001 From: mirakyux Date: Wed, 25 Nov 2026 16:11:58 +0800 Subject: [PATCH 1/6] feat(editor): add rainbow coloring and document highlights --- rust/contracts/rust-core-api.md | 45 +++++- rust/crates/core/src/protocol/command.rs | 6 + .../core/src/runtime/dispatcher/editor.rs | 6 + rust/crates/core/src/tests/editor_dispatch.rs | 49 ++++++- rust/crates/editor/src/lib.rs | 4 +- rust/crates/editor/src/preferences.rs | 79 ++++++++++- rust/crates/editor/src/rainbow_brackets.rs | 131 ++++++++++++++++++ rust/crates/editor/src/rainbow_variables.rs | 111 +++++++++++++++ .../lsp-client/src/client/capabilities.rs | 7 + .../crates/lsp-client/src/client/lifecycle.rs | 1 + rust/crates/lsp-client/src/client/requests.rs | 1 + rust/crates/lsp-client/src/client/results.rs | 20 +++ .../lsp-client/src/client/validation.rs | 1 + rust/crates/lsp-engine/src/operations.rs | 2 + rust/crates/lsp-engine/src/requests.rs | 2 + rust/crates/lsp-engine/src/tests.rs | 52 +++++++ rust/fixtures/editor/ide-essentials-v1.json | 6 +- rust/fixtures/editor/rainbow-brackets-v1.json | 84 +++++++++++ .../fixtures/editor/rainbow-variables-v1.json | 59 ++++++++ rust/fixtures/lsp/document-highlight-v1.json | 20 +++ 20 files changed, 679 insertions(+), 7 deletions(-) create mode 100644 rust/crates/editor/src/rainbow_brackets.rs create mode 100644 rust/crates/editor/src/rainbow_variables.rs create mode 100644 rust/fixtures/editor/rainbow-brackets-v1.json create mode 100644 rust/fixtures/editor/rainbow-variables-v1.json create mode 100644 rust/fixtures/lsp/document-highlight-v1.json diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 372fa950..20feb522 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -724,6 +724,8 @@ or removing a command fails until the table changes in the same commit. | `editor.copyReferenceLocation` | Format a one-based line reference from normalized document symbols; fall back to a file path when no containing symbol exists | | `editor.find` | Find text or plans bounded replacements in a borrowed document | | `editor.preferences.resolve` | Resolve persisted editor presentation preferences | +| `editor.rainbowBrackets` | Match bounded structural bracket tokens and assign their nesting depths | +| `editor.rainbowVariables` | Assign stable palette values to bounded variable tokens | | `editor.recent.reduce` | Reduce and queries bounded recent-file history | | `editor.recovery.decide` | Decide how a native checkpoint should recover | | `keymap.schemes.reduce` | Reduce named shortcut schemes (from `lithe-core-rules`) | @@ -6805,6 +6807,16 @@ Missing means `true`, the previous behaviour; the usages shown from a declaration (`lsp.declarationOrUsages`) pass `false` so the language server leaves the declaration out. Other operations ignore the field. +Operation `documentHighlight` (`textDocument/documentHighlight`) takes a +document `uri` and a zero-based `position` with a UTF-16 column. Core advertises +dynamic registration. The operation is offered when the server declares +`documentHighlightProvider` or dynamically registers the method. The asynchronous +completion carries `{ ranges: LspRange[] }` for occurrences in that document. +Ranges use `line` and `utf16Column` and retain server order, up to 4096 valid +nonempty ranges. Invalid entries are dropped, and a null or non-array result +returns an empty array. Core omits the optional server highlight kind. +Fixture: `rust/fixtures/lsp/document-highlight-v1.json`. + Completion requests accept optional `completionContext` with LSP `triggerKind` (`1` invoked, `2` trigger character, `3` incomplete-list refresh) and `triggerCharacter` (required and one character for kind `2`). Missing context @@ -8600,9 +8612,40 @@ replacement fails atomically. Invalid requests return `invalid_request` with sta Source, query and replacement are never included in errors or diagnostic logs. `editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`, -`cursorStyle` (`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`. +`cursorStyle` (`line`, `block`, `underline`), `cursorBlink`, `autoSaveDelayMilliseconds`, +`rainbowBrackets`, `rainbowVariables`, `rainbowBracketLightColors` and +`rainbowBracketDarkColors`. It returns actual values and minimum/maximum delay. Defaults: true, false, true, line, true, 1500 ms; unknown styles resolve to line and delay clamps to 250–60,000 ms. +Rainbow brackets and variable coloring are independent options that default to +disabled and share the light and dark palettes. Each palette accepts one to eight +`#RRGGBB` strings with optional surrounding whitespace and case-insensitive ASCII +hex. Core returns uppercase values. An absent, empty or malformed palette uses +the default palette for that theme, independently of the other theme. + +`editor.rainbowBrackets` accepts `{brackets:[{offset,bracket}]}` and returns +`{colors:[{offset,depth,matchOffset?}]}` in input order. Offsets are zero-based UTF-8 byte +positions and must increase strictly. The offset and the exclusive end of its +one-byte range must fit an unsigned 32-bit integer. Allowed tokens are `()[]{}`, +with at most 10,000 tokens per request. The host supplies tokens from its +language tokenizer and omits tokens in comments or literals. Each opener is +colored by its zero-based nesting depth, and a matching closer uses the same +depth. Both ends of a matched pair include the other end's byte offset as +`matchOffset`. An unmatched opener keeps its color and has no `matchOffset`. +An unmatched or mismatched closer keeps its base color and leaves open pairs +intact. Core returns `invalid_request` for invalid token data or offsets +and for requests that exceed the token limit. + +`editor.rainbowVariables` accepts `{variables:[{start,end,name}]}` and returns +`{colors:[{start,end,color}]}` in input order. The host supplies variable tokens +classified by its language or semantic tokenizer. The `start` and `end` values +are unsigned 32-bit UTF-8 byte offsets forming a nonempty half-open range. The +ranges must be in document order and must not overlap. A request is limited to +10,000 ranges. Each name must contain 1–256 UTF-8 bytes and match the length of +its range. Core computes `color` as unsigned 32-bit FNV-1a over the exact name +bytes, preserving case. A host takes the result modulo the active palette +length. Core returns `invalid_request` for malformed requests and bounds +violations. `editor.recent.reduce` accepts `entries`, optional `event:{kind,path,name,line,column}`, `query` and `onlyEdited`. It returns bounded `entries` and filtered `results`. Paths are diff --git a/rust/crates/core/src/protocol/command.rs b/rust/crates/core/src/protocol/command.rs index 3d1bbc87..a77025b5 100644 --- a/rust/crates/core/src/protocol/command.rs +++ b/rust/crates/core/src/protocol/command.rs @@ -669,6 +669,10 @@ pub enum EditorCommand { Find, /// Resolves persisted editor presentation preferences (`editor.preferences.resolve`). PreferencesResolve, + /// Assigns nesting depths to structural bracket tokens (`editor.rainbowBrackets`). + RainbowBrackets, + /// Assigns stable, spelling-based colors to variable tokens (`editor.rainbowVariables`). + RainbowVariables, /// Reduces and queries bounded recent-file history (`editor.recent.reduce`). RecentReduce, /// Decides how a native checkpoint should recover (`editor.recovery.decide`). @@ -1552,6 +1556,8 @@ impl CoreCommand { } "editor.find" => Some(Self::Editor(EditorCommand::Find)), "editor.preferences.resolve" => Some(Self::Editor(EditorCommand::PreferencesResolve)), + "editor.rainbowBrackets" => Some(Self::Editor(EditorCommand::RainbowBrackets)), + "editor.rainbowVariables" => Some(Self::Editor(EditorCommand::RainbowVariables)), "editor.recent.reduce" => Some(Self::Editor(EditorCommand::RecentReduce)), "editor.recovery.decide" => Some(Self::Editor(EditorCommand::RecoveryDecide)), "keymap.schemes.reduce" => Some(Self::Keymap(KeymapCommand::SchemesReduce)), diff --git a/rust/crates/core/src/runtime/dispatcher/editor.rs b/rust/crates/core/src/runtime/dispatcher/editor.rs index f02b0239..a4681ae0 100644 --- a/rust/crates/core/src/runtime/dispatcher/editor.rs +++ b/rust/crates/core/src/runtime/dispatcher/editor.rs @@ -33,6 +33,12 @@ pub(super) fn dispatch( EditorCommand::PreferencesResolve => { plugin_response(id, payload, lithe_editor::preferences::resolve_command) } + EditorCommand::RainbowBrackets => { + plugin_response(id, payload, lithe_editor::rainbow_brackets::color_command) + } + EditorCommand::RainbowVariables => { + plugin_response(id, payload, lithe_editor::rainbow_variables::color_command) + } EditorCommand::RecentReduce => { plugin_response(id, payload, lithe_editor::recent::reduce_command) } diff --git a/rust/crates/core/src/tests/editor_dispatch.rs b/rust/crates/core/src/tests/editor_dispatch.rs index d57aa7f0..07cf2867 100644 --- a/rust/crates/core/src/tests/editor_dispatch.rs +++ b/rust/crates/core/src/tests/editor_dispatch.rs @@ -1,9 +1,54 @@ //! The `editor.*` commands through the JSON dispatcher: shared fixtures for -//! navigation input, text edit plans and navigation history, and the request -//! envelope for malformed payloads. +//! navigation input, text edit plans, navigation history and rainbow coloring. use serde_json::{json, Value}; +#[test] +fn rainbow_brackets_match_shared_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/editor/rainbow-brackets-v1.json" + )) + .unwrap(); + assert_eq!( + fixture["maxBrackets"], + lithe_editor::rainbow_brackets::MAX_BRACKETS + ); + assert_rainbow_fixture(&fixture); +} + +#[test] +fn rainbow_variables_match_shared_fixture() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../../fixtures/editor/rainbow-variables-v1.json" + )) + .unwrap(); + assert_eq!( + fixture["maxVariables"], + lithe_editor::rainbow_variables::MAX_VARIABLES + ); + assert_eq!( + fixture["maxNameBytes"], + lithe_editor::rainbow_variables::MAX_NAME_BYTES + ); + assert_rainbow_fixture(&fixture); +} + +fn assert_rainbow_fixture(fixture: &Value) { + for case in fixture["cases"].as_array().unwrap() { + let response: Value = serde_json::from_str(&crate::execute_json( + &json!({"command": fixture["command"], "payload": case["payload"]}).to_string(), + )) + .unwrap(); + if let Some(code) = case.get("expectedError") { + assert_eq!(response["ok"], false, "{}: {response}", case["name"]); + assert_eq!(response["error"]["code"], *code, "{}", case["name"]); + } else { + assert_eq!(response["ok"], true, "{}: {response}", case["name"]); + assert_eq!(response["data"], case["expected"], "{}", case["name"]); + } + } +} + #[test] fn navigation_input_matches_shared_fixture() { let fixture: Value = serde_json::from_str(include_str!( diff --git a/rust/crates/editor/src/lib.rs b/rust/crates/editor/src/lib.rs index 1285e80d..ac984c97 100644 --- a/rust/crates/editor/src/lib.rs +++ b/rust/crates/editor/src/lib.rs @@ -1,6 +1,6 @@ //! Editor commands owned by Rust Core: deterministic line edits, find, //! plugin text edit plans, navigation input and history, editor -//! preferences, recent files and crash-recovery decisions. +//! preferences, rainbow coloring, recent files and crash-recovery decisions. //! //! Hosts apply the returned replacements and states through their own text //! engine. The `editor.*` JSON commands are dispatched by `lithe-core`. @@ -10,6 +10,8 @@ pub mod line_edit; pub mod navigation_history; pub mod navigation_input; pub mod preferences; +pub mod rainbow_brackets; +pub mod rainbow_variables; pub mod recent; pub mod recovery; pub mod reference_location; diff --git a/rust/crates/editor/src/preferences.rs b/rust/crates/editor/src/preferences.rs index 9d702454..6559b437 100644 --- a/rust/crates/editor/src/preferences.rs +++ b/rust/crates/editor/src/preferences.rs @@ -4,6 +4,14 @@ use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; +const MAX_RAINBOW_COLORS: usize = 8; +const LIGHT_BRACKET_COLORS: &[&str] = &[ + "#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68", +]; +const DARK_BRACKET_COLORS: &[&str] = &[ + "#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4", +]; + #[derive(Default, Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] struct Stored { @@ -13,10 +21,32 @@ struct Stored { cursor_style: Option, cursor_blink: Option, auto_save_delay_milliseconds: Option, + rainbow_brackets: Option, + rainbow_variables: Option, + // Retain each raw palette independently so a malformed color can fall + // back without discarding the other persisted preferences. + rainbow_bracket_light_colors: Option, + rainbow_bracket_dark_colors: Option, +} + +fn effective_palette(stored: Option<&Value>, defaults: &[&str]) -> Vec { + stored + .and_then(Value::as_array) + .filter(|colors| (1..=MAX_RAINBOW_COLORS).contains(&colors.len())) + .and_then(|colors| colors.iter().map(normalize_color).collect()) + .unwrap_or_else(|| defaults.iter().map(|color| (*color).to_owned()).collect()) +} + +fn normalize_color(value: &Value) -> Option { + let color = value.as_str()?.trim(); + let digits = color.strip_prefix('#')?; + (digits.len() == 6 && digits.bytes().all(|byte| byte.is_ascii_hexdigit())) + .then(|| color.to_ascii_uppercase()) } /// Resolves stored editor preferences into effective values, filling in -/// defaults and clamping the auto-save delay (`editor.preferences.resolve`). +/// defaults, normalizing rainbow palettes and clamping the auto-save delay +/// (`editor.preferences.resolve`). pub fn resolve_command(payload: Value) -> Result { let stored: Stored = serde_json::from_value(payload) .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid editor preferences"))?; @@ -33,7 +63,11 @@ pub fn resolve_command(payload: Value) -> Result { "cursorBlink":stored.cursor_blink.unwrap_or(true), "autoSaveDelayMilliseconds":stored.auto_save_delay_milliseconds.unwrap_or(1500).clamp(250,60_000), "minimumAutoSaveDelayMilliseconds":250, - "maximumAutoSaveDelayMilliseconds":60_000 + "maximumAutoSaveDelayMilliseconds":60_000, + "rainbowBrackets":stored.rainbow_brackets.unwrap_or(false), + "rainbowVariables":stored.rainbow_variables.unwrap_or(false), + "rainbowBracketLightColors":effective_palette(stored.rainbow_bracket_light_colors.as_ref(), LIGHT_BRACKET_COLORS), + "rainbowBracketDarkColors":effective_palette(stored.rainbow_bracket_dark_colors.as_ref(), DARK_BRACKET_COLORS) })) } @@ -49,6 +83,16 @@ mod tests { assert_eq!(value["cursorStyle"], "line"); assert_eq!(value["cursorBlink"], true); assert_eq!(value["autoSaveDelayMilliseconds"], 1500); + assert_eq!(value["rainbowBrackets"], false); + assert_eq!(value["rainbowVariables"], false); + assert_eq!( + value["rainbowBracketLightColors"], + json!(LIGHT_BRACKET_COLORS) + ); + assert_eq!( + value["rainbowBracketDarkColors"], + json!(DARK_BRACKET_COLORS) + ); } #[test] fn corrupted_values_are_bounded_without_replacing_valid_choices() { @@ -59,4 +103,35 @@ mod tests { assert_eq!(value["cursorBlink"], false); assert_eq!(value["autoSaveDelayMilliseconds"], 250); } + + #[test] + fn rainbow_palettes_normalize_and_fall_back_independently() { + for bad_palette in [ + json!([]), + json!(["#GG0000"]), + json!(["#123456", 0]), + json!("#123456"), + json!(vec!["#123456"; MAX_RAINBOW_COLORS + 1]), + ] { + let value = resolve_command(json!({ + "lineNumbers": false, + "rainbowBrackets": true, + "rainbowVariables": true, + "rainbowBracketLightColors": bad_palette, + "rainbowBracketDarkColors": [" #aabbcc ", "#D3D3D3"], + })) + .unwrap(); + assert_eq!(value["lineNumbers"], false); + assert_eq!(value["rainbowBrackets"], true); + assert_eq!(value["rainbowVariables"], true); + assert_eq!( + value["rainbowBracketLightColors"], + json!(LIGHT_BRACKET_COLORS) + ); + assert_eq!( + value["rainbowBracketDarkColors"], + json!(["#AABBCC", "#D3D3D3"]) + ); + } + } } diff --git a/rust/crates/editor/src/rainbow_brackets.rs b/rust/crates/editor/src/rainbow_brackets.rs new file mode 100644 index 00000000..bd3f6628 --- /dev/null +++ b/rust/crates/editor/src/rainbow_brackets.rs @@ -0,0 +1,131 @@ +//! Matching pairs and nesting depths for structural brackets identified by the host's tokenizer. + +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +/// Maximum number of bracket tokens and colors in one request. +pub const MAX_BRACKETS: usize = 10_000; + +#[derive(Clone, Copy, Deserialize, PartialEq)] +enum Bracket { + #[serde(rename = "(")] + OpenParen, + #[serde(rename = ")")] + CloseParen, + #[serde(rename = "[")] + OpenSquare, + #[serde(rename = "]")] + CloseSquare, + #[serde(rename = "{")] + OpenBrace, + #[serde(rename = "}")] + CloseBrace, +} + +impl Bracket { + fn closing(self) -> Option { + match self { + Self::OpenParen => Some(Self::CloseParen), + Self::OpenSquare => Some(Self::CloseSquare), + Self::OpenBrace => Some(Self::CloseBrace), + Self::CloseParen | Self::CloseSquare | Self::CloseBrace => None, + } + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Token { + /// Zero-based UTF-8 byte offset into the host-owned document snapshot. + offset: u32, + bracket: Bracket, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + /// Structural tokens in strictly increasing byte offset order. + brackets: Vec, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Color { + offset: u32, + /// Zero-based nesting depth, before wrapping to the active palette size. + depth: u32, + /// Byte offset of the other end, absent until the bracket has a partner. + #[serde(skip_serializing_if = "Option::is_none")] + match_offset: Option, +} + +/// Returns both endpoints of each matched pair at the same nesting depth. +/// A mismatched closer is omitted and leaves the stack available for a later +/// match. Openers retain their current depth while the document is incomplete. +pub fn color_command(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload) + .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid rainbow bracket tokens"))?; + if request.brackets.len() > MAX_BRACKETS { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Rainbow bracket tokens exceed 10000 entries", + )); + } + + let mut previous_offset = None; + let mut expected_closers = Vec::new(); + let mut colors: Vec = Vec::with_capacity(request.brackets.len()); + for token in request.brackets { + // The host uses a one-byte range, so its exclusive end must fit too. + if token.offset == u32::MAX || previous_offset.is_some_and(|offset| token.offset <= offset) + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Rainbow bracket offsets must be strictly increasing with a representable end", + )); + } + previous_offset = Some(token.offset); + + let (depth, match_offset) = if let Some(closing) = token.bracket.closing() { + let depth = expected_closers.len(); + expected_closers.push((closing, colors.len())); + (depth, None) + } else if let Some(&(_, opener)) = expected_closers + .last() + .filter(|(closing, _)| *closing == token.bracket) + { + expected_closers.pop(); + colors[opener].match_offset = Some(token.offset); + (expected_closers.len(), Some(colors[opener].offset)) + } else { + continue; + }; + colors.push(Color { + offset: token.offset, + depth: depth as u32, + match_offset, + }); + } + Ok(json!({ "colors": colors })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn accepts_the_token_limit_and_rejects_the_next_token() { + let mut brackets: Vec = (0..MAX_BRACKETS) + .map(|offset| json!({"offset": offset, "bracket": "("})) + .collect(); + let result = color_command(json!({"brackets": &brackets})).unwrap(); + let colors = result["colors"].as_array().unwrap(); + assert_eq!(colors.len(), MAX_BRACKETS); + assert_eq!(colors[MAX_BRACKETS - 1]["depth"], MAX_BRACKETS - 1); + + brackets.push(json!({"offset": MAX_BRACKETS, "bracket": "("})); + let error = color_command(json!({"brackets": brackets})).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + } +} diff --git a/rust/crates/editor/src/rainbow_variables.rs b/rust/crates/editor/src/rainbow_variables.rs new file mode 100644 index 00000000..0914bab5 --- /dev/null +++ b/rust/crates/editor/src/rainbow_variables.rs @@ -0,0 +1,111 @@ +//! Stable palette selection for variable tokens identified by the host. + +use lithe_protocol::{CoreError, ErrorCode}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +/// Maximum number of variable ranges accepted in one request. +pub const MAX_VARIABLES: usize = 10_000; +/// Maximum number of UTF-8 bytes in a variable name. +pub const MAX_NAME_BYTES: usize = 256; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Variable { + /// Inclusive UTF-8 byte offset into the host's document snapshot. + start: u32, + /// Exclusive UTF-8 byte offset into the host's document snapshot. + end: u32, + /// Exact spelling at the byte range, with case preserved. + name: String, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Request { + /// Variable tokens in document order with no overlapping byte ranges. + variables: Vec, +} + +#[derive(Serialize)] +struct Color { + start: u32, + end: u32, + /// Stable hash reduced to a slot by the active theme's palette length. + color: u32, +} + +/// Assigns one deterministic color value per variable range. Equal spellings +/// receive the same value across documents, sessions and platforms. +pub fn color_command(payload: Value) -> Result { + let request: Request = serde_json::from_value(payload).map_err(|_| { + CoreError::new(ErrorCode::InvalidRequest, "Invalid rainbow variable tokens") + })?; + if request.variables.len() > MAX_VARIABLES { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Rainbow variable tokens exceed 10000 entries", + )); + } + + let mut previous_end = 0; + let mut colors = Vec::with_capacity(request.variables.len()); + for variable in request.variables { + let name_bytes = variable.name.len(); + if variable.start < previous_end + || variable.start >= variable.end + || name_bytes > MAX_NAME_BYTES + || (variable.end - variable.start) as usize != name_bytes + { + return Err(CoreError::new( + ErrorCode::InvalidRequest, + "Rainbow variable ranges must be ordered, non-overlapping and match their bounded UTF-8 names", + )); + } + previous_end = variable.end; + colors.push(Color { + start: variable.start, + end: variable.end, + color: name_color(&variable.name), + }); + } + Ok(json!({ "colors": colors })) +} + +fn name_color(name: &str) -> u32 { + // FNV-1a over the original UTF-8 bytes keeps palettes stable when + // document ranges move, regardless of process-local hash seeds. + let mut hash = 0x811c_9dc5_u32; + for byte in name.bytes() { + hash ^= u32::from(byte); + hash = hash.wrapping_mul(0x0100_0193); + } + hash +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn enforces_token_and_name_budgets() { + let mut variables: Vec = (0..MAX_VARIABLES) + .map(|start| json!({"start":start,"end":start+1,"name":"a"})) + .collect(); + let result = color_command(json!({"variables":&variables})).unwrap(); + let colors = result["colors"].as_array().unwrap(); + assert_eq!(colors.len(), MAX_VARIABLES); + assert_eq!(colors[MAX_VARIABLES - 1]["color"], 3_826_002_220_u32); + + variables.push(json!({"start":MAX_VARIABLES,"end":MAX_VARIABLES+1,"name":"a"})); + let error = color_command(json!({"variables":variables})).unwrap_err(); + assert!(matches!(error.code, ErrorCode::InvalidRequest)); + + for (name_bytes, valid) in [(MAX_NAME_BYTES, true), (MAX_NAME_BYTES + 1, false)] { + let result = color_command(json!({ + "variables":[{"start":0,"end":name_bytes,"name":"a".repeat(name_bytes)}] + })); + assert_eq!(result.is_ok(), valid); + } + } +} diff --git a/rust/crates/lsp-client/src/client/capabilities.rs b/rust/crates/lsp-client/src/client/capabilities.rs index b3993c78..59b2f88e 100644 --- a/rust/crates/lsp-client/src/client/capabilities.rs +++ b/rust/crates/lsp-client/src/client/capabilities.rs @@ -78,6 +78,12 @@ pub(crate) fn feature_names_from_capabilities(capabilities: &Value) -> Vec Option<&'static str> { "textDocument/typeDefinition" => Some("typeDefinition"), "textDocument/implementation" => Some("implementation"), "textDocument/references" => Some("references"), + "textDocument/documentHighlight" => Some("documentHighlight"), "textDocument/hover" => Some("hover"), "textDocument/signatureHelp" => Some("signatureHelp"), "textDocument/completion" => Some("completion"), diff --git a/rust/crates/lsp-client/src/client/lifecycle.rs b/rust/crates/lsp-client/src/client/lifecycle.rs index 03f6990c..2648d4ba 100644 --- a/rust/crates/lsp-client/src/client/lifecycle.rs +++ b/rust/crates/lsp-client/src/client/lifecycle.rs @@ -74,6 +74,7 @@ pub fn client_initialize_for_plugin( "typeDefinition": { "dynamicRegistration": true }, "implementation": { "dynamicRegistration": true }, "references": { "dynamicRegistration": true }, + "documentHighlight": { "dynamicRegistration": true }, "rename": { "dynamicRegistration": true }, "formatting": { "dynamicRegistration": true }, "rangeFormatting": { "dynamicRegistration": true }, diff --git a/rust/crates/lsp-client/src/client/requests.rs b/rust/crates/lsp-client/src/client/requests.rs index 713c291c..c9d49263 100644 --- a/rust/crates/lsp-client/src/client/requests.rs +++ b/rust/crates/lsp-client/src/client/requests.rs @@ -42,6 +42,7 @@ pub(crate) fn feature_request_params(request: &ClientFeatureRequest) -> Result Ok(json!({ "textDocument": text_document, "position": lsp_position_json(required_position(request)?) diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs index 9cf649d5..f88ee6b4 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -39,6 +39,9 @@ pub(crate) fn lsp_feature_result_for_method( Some("textDocument/documentSymbol") => Some(json!({ "symbols": parse_document_symbols(result) })), + Some("textDocument/documentHighlight") => Some(json!({ + "ranges": parse_document_highlights(result) + })), Some("textDocument/inlayHint") => Some(json!({ "hints": parse_inlay_hints(result) })), @@ -713,6 +716,23 @@ fn parse_document_symbol(item: &Value) -> Option { })) } +/// Retains only nonempty, ordered ranges and bounds the payload sent to the editor. +fn parse_document_highlights(result: &Value) -> Vec { + const MAX_HIGHLIGHTS: usize = 4096; + result + .as_array() + .into_iter() + .flatten() + .filter_map(|highlight| { + let range = parse_lsp_range(highlight.get("range")?)?; + let start = (range.start.line, range.start.utf16_column); + let end = (range.end.line, range.end.utf16_column); + (start.0 >= 0 && start.1 >= 0 && end.1 >= 0 && start < end).then_some(range) + }) + .take(MAX_HIGHLIGHTS) + .collect() +} + fn parse_folding_ranges(result: &Value) -> Vec { result .as_array() diff --git a/rust/crates/lsp-client/src/client/validation.rs b/rust/crates/lsp-client/src/client/validation.rs index 1c1b8215..f9e393a3 100644 --- a/rust/crates/lsp-client/src/client/validation.rs +++ b/rust/crates/lsp-client/src/client/validation.rs @@ -83,6 +83,7 @@ pub(crate) fn validate_lsp_method(method: &str) -> Result<(), CoreError> { | "textDocument/typeDefinition" | "textDocument/implementation" | "textDocument/references" + | "textDocument/documentHighlight" | "textDocument/rename" | "textDocument/formatting" | "textDocument/rangeFormatting" diff --git a/rust/crates/lsp-engine/src/operations.rs b/rust/crates/lsp-engine/src/operations.rs index 085ce777..6698854d 100644 --- a/rust/crates/lsp-engine/src/operations.rs +++ b/rust/crates/lsp-engine/src/operations.rs @@ -956,6 +956,7 @@ pub(crate) fn semantic_method(operation: LspSemanticOperation) -> &'static str { LspSemanticOperation::Declaration => "textDocument/declaration", LspSemanticOperation::TypeDefinition => "textDocument/typeDefinition", LspSemanticOperation::References => "textDocument/references", + LspSemanticOperation::DocumentHighlight => "textDocument/documentHighlight", LspSemanticOperation::Implementation => "textDocument/implementation", LspSemanticOperation::Rename => "textDocument/rename", LspSemanticOperation::Formatting => "textDocument/formatting", @@ -984,6 +985,7 @@ fn semantic_capability(operation: LspSemanticOperation) -> Option<&'static str> LspSemanticOperation::Declaration => Some("declaration"), LspSemanticOperation::TypeDefinition => Some("typeDefinition"), LspSemanticOperation::References => Some("references"), + LspSemanticOperation::DocumentHighlight => Some("documentHighlight"), LspSemanticOperation::Implementation => Some("implementation"), LspSemanticOperation::Rename => Some("rename"), LspSemanticOperation::Formatting => Some("formatting"), diff --git a/rust/crates/lsp-engine/src/requests.rs b/rust/crates/lsp-engine/src/requests.rs index f99ce8b3..986b2007 100644 --- a/rust/crates/lsp-engine/src/requests.rs +++ b/rust/crates/lsp-engine/src/requests.rs @@ -199,6 +199,8 @@ pub enum LspSemanticOperation { TypeDefinition, /// `textDocument/references`. References, + /// `textDocument/documentHighlight`: occurrences in the current document. + DocumentHighlight, /// `textDocument/implementation`. Implementation, /// `textDocument/rename`. diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index 75f34a6c..cde0d667 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -2253,6 +2253,58 @@ fn partial_frames_are_buffered_and_consecutive_frames_arrive_in_order() { assert_eq!(harness.snapshot().state, LspLifecycleState::Ready); } +#[test] +fn document_highlight_routes_and_normalizes_document_ranges() { + let fixture: Value = serde_json::from_str(include_str!( + "../../../fixtures/lsp/document-highlight-v1.json" + )) + .unwrap(); + let method = "textDocument/documentHighlight"; + let uri = fixture["uri"].as_str().unwrap(); + let mut harness = Harness::start(|_| {}); + let initialize = harness.server.await_request("initialize").unwrap(); + assert_eq!( + harness.written_request(&initialize)["params"]["capabilities"]["textDocument"] + ["documentHighlight"]["dynamicRegistration"], + true + ); + harness + .server + .complete_initialize(json!({"documentHighlightProvider": true})); + harness.await_state(LspLifecycleState::Ready); + harness.sync( + uri, + "package main\nvar a, name = 0, \"text\"\nvar _ = \"😀\" + name", + ); + + let line = fixture["position"]["line"].as_i64().unwrap(); + let column = fixture["position"]["utf16Column"].as_i64().unwrap(); + for (index, (server_result, expected)) in [ + (fixture["serverResult"].clone(), fixture["expected"].clone()), + (Value::Null, json!({"ranges": []})), + ] + .into_iter() + .enumerate() + { + let operation = + harness.request_at(LspSemanticOperation::DocumentHighlight, uri, line, column); + let request = harness.server.await_request_at(method, index).unwrap(); + assert_eq!( + harness.written_request(&request)["params"], + json!({"textDocument": {"uri": uri}, "position": {"line": line, "character": column}}) + ); + harness + .server + .send(json!({"jsonrpc": "2.0", "id": request, "result": server_result})); + let done = harness.await_event(|event| { + event.kind == "requestCompleted" + && event.operation_id.as_deref() == Some(operation.as_str()) + }); + assert_eq!(done.method.as_deref(), Some(method)); + assert_eq!(done.result.as_ref(), Some(&expected)); + } +} + /// Criterion 14: dynamic registration and unregistration change availability. #[test] fn features_event_reports_completion_trigger_characters() { diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index fd5e1ad1..95ce876a 100644 --- a/rust/fixtures/editor/ide-essentials-v1.json +++ b/rust/fixtures/editor/ide-essentials-v1.json @@ -63,7 +63,11 @@ "cursorBlink": true, "autoSaveDelayMilliseconds": 1500, "minimumAutoSaveDelayMilliseconds": 250, - "maximumAutoSaveDelayMilliseconds": 60000 + "maximumAutoSaveDelayMilliseconds": 60000, + "rainbowBrackets": false, + "rainbowVariables": false, + "rainbowBracketLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], + "rainbowBracketDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] } }, { diff --git a/rust/fixtures/editor/rainbow-brackets-v1.json b/rust/fixtures/editor/rainbow-brackets-v1.json new file mode 100644 index 00000000..a6db6d90 --- /dev/null +++ b/rust/fixtures/editor/rainbow-brackets-v1.json @@ -0,0 +1,84 @@ +{ + "version": 1, + "command": "editor.rainbowBrackets", + "maxBrackets": 10000, + "cases": [ + { + "name": "nested-and-sibling-pairs", + "payload": { + "brackets": [ + { "offset": 0, "bracket": "{" }, + { "offset": 9, "bracket": "[" }, + { "offset": 12, "bracket": "(" }, + { "offset": 13, "bracket": ")" }, + { "offset": 15, "bracket": "]" }, + { "offset": 19, "bracket": "[" }, + { "offset": 22, "bracket": "]" }, + { "offset": 23, "bracket": "}" } + ] + }, + "expected": { + "colors": [ + { "offset": 0, "depth": 0, "matchOffset": 23 }, + { "offset": 9, "depth": 1, "matchOffset": 15 }, + { "offset": 12, "depth": 2, "matchOffset": 13 }, + { "offset": 13, "depth": 2, "matchOffset": 12 }, + { "offset": 15, "depth": 1, "matchOffset": 9 }, + { "offset": 19, "depth": 1, "matchOffset": 22 }, + { "offset": 22, "depth": 1, "matchOffset": 19 }, + { "offset": 23, "depth": 0, "matchOffset": 0 } + ] + } + }, + { + "name": "unmatched-closers-and-openers", + "payload": { + "brackets": [ + { "offset": 0, "bracket": "]" }, + { "offset": 2, "bracket": "{" }, + { "offset": 3, "bracket": "[" }, + { "offset": 4, "bracket": "}" }, + { "offset": 5, "bracket": "]" }, + { "offset": 6, "bracket": "(" } + ] + }, + "expected": { + "colors": [ + { "offset": 2, "depth": 0 }, + { "offset": 3, "depth": 1, "matchOffset": 5 }, + { "offset": 5, "depth": 1, "matchOffset": 3 }, + { "offset": 6, "depth": 1 } + ] + } + }, + { + "name": "no-tokens", + "payload": { "brackets": [] }, + "expected": { "colors": [] } + }, + { + "name": "unsupported-token", + "payload": { "brackets": [{ "offset": 3, "bracket": "<" }] }, + "expectedError": "invalid_request" + }, + { + "name": "duplicate-offset", + "payload": { + "brackets": [{ "offset": 0, "bracket": "(" }, { "offset": 0, "bracket": ")" }] + }, + "expectedError": "invalid_request" + }, + { + "name": "descending-offset", + "payload": { + "brackets": [{ "offset": 2, "bracket": "(" }, { "offset": 1, "bracket": ")" }] + }, + "expectedError": "invalid_request" + }, + { + "name": "unrepresentable-range-end", + "payload": { "brackets": [{ "offset": 4294967295, "bracket": "(" }] }, + "expectedError": "invalid_request" + } + ] +} diff --git a/rust/fixtures/editor/rainbow-variables-v1.json b/rust/fixtures/editor/rainbow-variables-v1.json new file mode 100644 index 00000000..5e32ccd0 --- /dev/null +++ b/rust/fixtures/editor/rainbow-variables-v1.json @@ -0,0 +1,59 @@ +{ + "version": 1, + "command": "editor.rainbowVariables", + "maxVariables": 10000, + "maxNameBytes": 256, + "cases": [ + { + "name": "case-sensitive-same-name-colors", + "payload": { + "variables": [ + { "start": 0, "end": 5, "name": "value" }, + { "start": 7, "end": 12, "name": "other" }, + { "start": 13, "end": 18, "name": "value" }, + { "start": 18, "end": 23, "name": "Value" }, + { "start": 25, "end": 31, "name": "变量" } + ] + }, + "expected": { + "colors": [ + { "start": 0, "end": 5, "color": 1113510858 }, + { "start": 7, "end": 12, "color": 3363671541 }, + { "start": 13, "end": 18, "color": 1113510858 }, + { "start": 18, "end": 23, "color": 3511155050 }, + { "start": 25, "end": 31, "color": 4246680784 } + ] + } + }, + { + "name": "no-tokens", + "payload": { "variables": [] }, + "expected": { "colors": [] } + }, + { + "name": "empty-range", + "payload": { "variables": [{ "start": 0, "end": 0, "name": "" }] }, + "expectedError": "invalid_request" + }, + { + "name": "reversed-range", + "payload": { "variables": [{ "start": 2, "end": 0, "name": "a" }] }, + "expectedError": "invalid_request" + }, + { + "name": "range-name-byte-length-mismatch", + "payload": { "variables": [{ "start": 0, "end": 2, "name": "变量" }] }, + "expectedError": "invalid_request" + }, + { + "name": "overlapping-ranges", + "payload": { + "variables": [ + { "start": 1, "end": 6, "name": "value" }, + { "start": 5, "end": 10, "name": "other" } + ] + }, + "expectedError": "invalid_request" + } + ] +} diff --git a/rust/fixtures/lsp/document-highlight-v1.json b/rust/fixtures/lsp/document-highlight-v1.json new file mode 100644 index 00000000..b1458c23 --- /dev/null +++ b/rust/fixtures/lsp/document-highlight-v1.json @@ -0,0 +1,20 @@ +{ + "version": 1, + "uri": "file:///workspace/main.go", + "position": {"line": 1, "utf16Column": 8}, + "serverResult": [ + {"range": {"start": {"line": 1, "character": 7}, "end": {"line": 1, "character": 11}}, "kind": 3}, + {"range": {"start": {"line": 2, "character": 15}, "end": {"line": 2, "character": 19}}}, + {"range": {"start": {"line": 3, "character": 9}, "end": {"line": 3, "character": 8}}}, + {"range": {"start": {"line": -1, "character": 2}, "end": {"line": 3, "character": 8}}}, + {"range": {"start": {"line": 3, "character": 8}, "end": {"line": 3, "character": 8}}}, + {"range": {"start": {"line": 3}, "end": {"line": 3, "character": 8}}}, + {"kind": 2} + ], + "expected": { + "ranges": [ + {"start": {"line": 1, "utf16Column": 7}, "end": {"line": 1, "utf16Column": 11}}, + {"start": {"line": 2, "utf16Column": 15}, "end": {"line": 2, "utf16Column": 19}} + ] + } +} From f3b816f0fe7fac2c93699d66bbf5cc4284ece84e Mon Sep 17 00:00:00 2001 From: mirakyux Date: Wed, 25 Nov 2026 17:06:42 +0800 Subject: [PATCH 2/6] feat(editor): resolve indent guide preferences --- rust/contracts/rust-core-api.md | 4 +++ rust/crates/editor/src/preferences.rs | 24 ++++++++++++++++++ rust/fixtures/editor/ide-essentials-v1.json | 28 +++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 20feb522..6170f99d 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -8612,11 +8612,15 @@ replacement fails atomically. Invalid requests return `invalid_request` with sta Source, query and replacement are never included in errors or diagnostic logs. `editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`, +`indentGuides`, `rainbowIndentGuides`, `cursorStyle` (`line`, `block`, `underline`), `cursorBlink`, `autoSaveDelayMilliseconds`, `rainbowBrackets`, `rainbowVariables`, `rainbowBracketLightColors` and `rainbowBracketDarkColors`. It returns actual values and minimum/maximum delay. Defaults: true, false, true, line, true, 1500 ms; unknown styles resolve to line and delay clamps to 250–60,000 ms. +Indent guides default to enabled and rainbow indent guides default to disabled. +The result returns both choices independently and adds `rainbowIndentGuidesEffective`, +which is true when both choices are enabled. Rainbow brackets and variable coloring are independent options that default to disabled and share the light and dark palettes. Each palette accepts one to eight `#RRGGBB` strings with optional surrounding whitespace and case-insensitive ASCII diff --git a/rust/crates/editor/src/preferences.rs b/rust/crates/editor/src/preferences.rs index 6559b437..d790a53f 100644 --- a/rust/crates/editor/src/preferences.rs +++ b/rust/crates/editor/src/preferences.rs @@ -17,6 +17,8 @@ const DARK_BRACKET_COLORS: &[&str] = &[ struct Stored { line_numbers: Option, whitespace: Option, + indent_guides: Option, + rainbow_indent_guides: Option, inlay_hints: Option, cursor_style: Option, cursor_blink: Option, @@ -55,9 +57,14 @@ pub fn resolve_command(payload: Value) -> Result { Some("underline") => "underline", _ => "line", }; + let indent_guides = stored.indent_guides.unwrap_or(true); + let rainbow_indent_guides = stored.rainbow_indent_guides.unwrap_or(false); Ok(json!({ "lineNumbers":stored.line_numbers.unwrap_or(true), "whitespace":stored.whitespace.unwrap_or(false), + "indentGuides":indent_guides, + "rainbowIndentGuides":rainbow_indent_guides, + "rainbowIndentGuidesEffective":indent_guides && rainbow_indent_guides, "inlayHints":stored.inlay_hints.unwrap_or(true), "cursorStyle":style, "cursorBlink":stored.cursor_blink.unwrap_or(true), @@ -79,6 +86,9 @@ mod tests { let value = resolve_command(json!({})).unwrap(); assert_eq!(value["lineNumbers"], true); assert_eq!(value["whitespace"], false); + assert_eq!(value["indentGuides"], true); + assert_eq!(value["rainbowIndentGuides"], false); + assert_eq!(value["rainbowIndentGuidesEffective"], false); assert_eq!(value["inlayHints"], true); assert_eq!(value["cursorStyle"], "line"); assert_eq!(value["cursorBlink"], true); @@ -94,6 +104,20 @@ mod tests { json!(DARK_BRACKET_COLORS) ); } + #[test] + fn rainbow_indent_guides_keep_the_choice_when_guides_are_hidden() { + for indent_guides in [false, true] { + let value = resolve_command(json!({ + "indentGuides": indent_guides, + "rainbowIndentGuides": true, + })) + .unwrap(); + assert_eq!(value["indentGuides"], indent_guides); + assert_eq!(value["rainbowIndentGuides"], true); + assert_eq!(value["rainbowIndentGuidesEffective"], indent_guides); + } + } + #[test] fn corrupted_values_are_bounded_without_replacing_valid_choices() { let value = resolve_command(json!({"lineNumbers":false,"inlayHints":false,"cursorStyle":"unknown","cursorBlink":false,"autoSaveDelayMilliseconds":1})).unwrap(); diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index 95ce876a..9321a228 100644 --- a/rust/fixtures/editor/ide-essentials-v1.json +++ b/rust/fixtures/editor/ide-essentials-v1.json @@ -58,6 +58,34 @@ "expected": { "lineNumbers": true, "whitespace": false, + "indentGuides": true, + "rainbowIndentGuides": false, + "rainbowIndentGuidesEffective": false, + "inlayHints": true, + "cursorStyle": "line", + "cursorBlink": true, + "autoSaveDelayMilliseconds": 1500, + "minimumAutoSaveDelayMilliseconds": 250, + "maximumAutoSaveDelayMilliseconds": 60000, + "rainbowBrackets": false, + "rainbowVariables": false, + "rainbowBracketLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], + "rainbowBracketDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] + } + }, + { + "name": "hidden-indent-guides-preserve-rainbow-choice", + "command": "editor.preferences.resolve", + "payload": { + "indentGuides": false, + "rainbowIndentGuides": true + }, + "expected": { + "lineNumbers": true, + "whitespace": false, + "indentGuides": false, + "rainbowIndentGuides": true, + "rainbowIndentGuidesEffective": false, "inlayHints": true, "cursorStyle": "line", "cursorBlink": true, From 71e1617f32ca4478125da1b8a027aa3b1b14fd43 Mon Sep 17 00:00:00 2001 From: mirakyux Date: Wed, 25 Nov 2026 21:22:07 +0800 Subject: [PATCH 3/6] feat(editor): add Unicode identifier search --- rust/contracts/rust-core-api.md | 10 +- rust/crates/core/src/runtime/ffi.rs | 17 +++- rust/crates/editor/src/find.rs | 100 ++++++++++++++++++-- rust/fixtures/editor/ide-essentials-v1.json | 44 +++++++++ 4 files changed, 156 insertions(+), 15 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 6170f99d..eedec8d3 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -8595,19 +8595,25 @@ Cancellation uses the operation ID registry, including cancellation checks betwe The host must run on a worker and guard the document snapshot and query generation before applying ranges or a replacement. This ABI adds no public plugin host methods. -The payload is `{query, caseSensitive?:false, wholeWord?:false, regex?:false, +The payload is `{query, caseSensitive?:false, wholeWord?:false, wholeIdentifier?:false, regex?:false, range?:{start,end}, replacement?:string, replaceStart?:number, caret?:0, backwards?:false}`. All offsets are original UTF-8 byte offsets, half-open and on rune boundaries. An omitted range searches the whole snapshot. Regex uses Unicode case folding/word boundaries and multiline anchors; regex replacement expands `$1`/`${name}` captures; literal replacement preserves dollar signs. `replaceStart` selects only that match; omitted means replace all. +For literal searches, `wholeIdentifier` checks both ends of a match against Unicode +`ID_Continue`, join controls and `$`, including adjacent characters outside a +scoped search. It takes precedence over `wholeWord`. Setting both +`wholeIdentifier` and `regex` to true returns `invalid_request` with +`regex_with_whole_identifier` in the details. Results are `{matches:[{start,end}],edits:[{start,end,text}],selected:number|null,truncated}`. Scoped requests also return `range`, adjusted for the planned replacement lengths so the selection remains valid after applying a bulk edit. Limits: 64 MiB source, 4096-byte query, 10,000 returned matches, 8 MiB total inserted text, 1 MiB compiled regex and 2 MiB DFA. A truncated search is useful for navigation but bulk replacement fails atomically. Invalid requests return `invalid_request` with stable details: -`invalid_request`, `missing_document`, `invalid_range`, `invalid_pattern`, `query_too_large`, +`invalid_request`, `missing_document`, `invalid_range`, `invalid_pattern`, +`regex_with_whole_identifier`, `query_too_large`, `source_too_large`, `source_too_large_or_invalid`, `replacement_too_large`, `too_many_matches`. Source, query and replacement are never included in errors or diagnostic logs. diff --git a/rust/crates/core/src/runtime/ffi.rs b/rust/crates/core/src/runtime/ffi.rs index 3e13e9b4..7379c662 100644 --- a/rust/crates/core/src/runtime/ffi.rs +++ b/rust/crates/core/src/runtime/ffi.rs @@ -307,11 +307,18 @@ mod editor_essentials_tests { let response: Value = unsafe { serde_json::from_str(CStr::from_ptr(pointer).to_str().unwrap()).unwrap() }; unsafe { lithe_core_free_string(pointer) }; - assert_eq!( - response["data"], case["expected"], - "{}: {}", - case["name"], response - ); + if let Some(error_code) = case["errorCode"].as_str() { + assert_eq!(response["ok"], false, "{}: {response}", case["name"]); + assert_eq!(response["error"]["code"], error_code, "{}", case["name"]); + assert_eq!( + response["error"]["details"], case["errorDetails"], + "{}", + case["name"] + ); + } else { + assert_eq!(response["ok"], true, "{}: {response}", case["name"]); + assert_eq!(response["data"], case["expected"], "{}", case["name"]); + } } } #[test] diff --git a/rust/crates/editor/src/find.rs b/rust/crates/editor/src/find.rs index 27d8b89d..4ce56566 100644 --- a/rust/crates/editor/src/find.rs +++ b/rust/crates/editor/src/find.rs @@ -4,9 +4,10 @@ //! keeps no text cache, and returns only byte ranges and requested replacements. use lithe_protocol::{cancellation, CoreError, ErrorCode}; -use regex::RegexBuilder; +use regex::{Regex, RegexBuilder}; use serde::Deserialize; use serde_json::{json, Value}; +use std::sync::LazyLock; const MAX_SOURCE_BYTES: usize = 64 * 1024 * 1024; const MAX_QUERY_BYTES: usize = 4096; @@ -21,6 +22,9 @@ struct Request { case_sensitive: bool, #[serde(default)] whole_word: bool, + /// For literal searches, treat Unicode ID_Continue, join controls and dollar signs as identifier continuations. + #[serde(default)] + whole_identifier: bool, #[serde(default)] regex: bool, range: Option, @@ -48,6 +52,17 @@ fn invalid(reason: &str) -> CoreError { .with_details(reason) } +fn identifier_continues(character: char) -> bool { + if character.is_ascii() { + return character.is_ascii_alphanumeric() || matches!(character, '_' | '$'); + } + static NON_ASCII_CONTINUATION: LazyLock = LazyLock::new(|| { + Regex::new(r"\A[\p{ID_Continue}\p{Join_Control}]\z") + .expect("identifier continuation uses supported Unicode properties") + }); + NON_ASCII_CONTINUATION.is_match(character.encode_utf8(&mut [0; 4])) +} + /// Finds matches in the borrowed document `source` and, when a replacement is /// requested, plans the edits (`editor.find`). /// @@ -58,6 +73,9 @@ fn invalid(reason: &str) -> CoreError { pub fn command(payload: Value, source: Option<&str>) -> Result { let request: Request = serde_json::from_value(payload).map_err(|_| invalid("invalid_request"))?; + if request.whole_identifier && request.regex { + return Err(invalid("regex_with_whole_identifier")); + } let source = source.ok_or_else(|| invalid("missing_document"))?; if source.len() > MAX_SOURCE_BYTES { return Err(invalid("source_too_large")); @@ -84,7 +102,7 @@ pub fn command(payload: Value, source: Option<&str>) -> Result } else { regex::escape(&request.query) }; - if request.whole_word { + if request.whole_word && !request.whole_identifier { pattern = format!(r"\b(?:{pattern})\b"); } let matcher = RegexBuilder::new(&pattern) @@ -103,15 +121,28 @@ pub fn command(payload: Value, source: Option<&str>) -> Result let mut removed_bytes = 0; for captures in matcher.captures_iter(text) { cancellation::check()?; - if matches.len() == MAX_MATCHES { - truncated = true; - break; - } let m = captures .get(0) .expect("a successful capture has a whole match"); let at = start + m.start(); - matches.push(json!({"start":at, "end":start + m.end()})); + let through = start + m.end(); + if request.whole_identifier + && (source[..at] + .chars() + .next_back() + .is_some_and(identifier_continues) + || source[through..] + .chars() + .next() + .is_some_and(identifier_continues)) + { + continue; + } + if matches.len() == MAX_MATCHES { + truncated = true; + break; + } + matches.push(json!({"start":at, "end":through})); if let Some(replacement) = &request.replacement { if request.replace_start.is_some_and(|wanted| wanted != at) { continue; @@ -127,7 +158,7 @@ pub fn command(payload: Value, source: Option<&str>) -> Result if replacement_bytes > MAX_REPLACEMENT_BYTES { return Err(invalid("replacement_too_large")); } - edits.push(json!({"start":at, "end":start + m.end(), "text":inserted})); + edits.push(json!({"start":at, "end":through, "text":inserted})); } } if truncated && request.replacement.is_some() && request.replace_start.is_none() { @@ -196,6 +227,59 @@ mod tests { assert_eq!(result["edits"], json!([{"start":14,"end":17,"text":"$1"}])); } + #[test] + fn whole_identifier_treats_dollar_as_continuation() { + let text = "$name $$name $name$ $nameSuffix name name$ $name"; + for (query, ranges) in [ + ("$name", json!([{"start":0,"end":5},{"start":43,"end":48}])), + ("name", json!([{"start":32,"end":36}])), + ] { + let result = command( + json!({"query":query,"caseSensitive":true,"wholeIdentifier":true}), + Some(text), + ) + .unwrap(); + assert_eq!(result["matches"], ranges); + } + } + + #[test] + fn whole_identifier_uses_unicode_identifier_continuations() { + let source = "foo ℘foo a·b ℘foo a·b b foo"; + for (query, ranges) in [ + ("foo", json!([{"start":0,"end":3},{"start":30,"end":33}])), + ("℘foo", json!([{"start":4,"end":10},{"start":16,"end":22}])), + ("a·b", json!([{"start":11,"end":15},{"start":23,"end":27}])), + ("b", json!([{"start":28,"end":29}])), + ] { + let result = command( + json!({"query":query,"caseSensitive":true,"wholeIdentifier":true}), + Some(source), + ) + .unwrap(); + assert_eq!(result["matches"], ranges, "query {query}"); + } + let scoped = command( + json!({"query":"foo","wholeIdentifier":true,"range":{"start":7,"end":10}}), + Some(source), + ) + .unwrap(); + assert_eq!(scoped["matches"], json!([])); + } + + #[test] + fn whole_identifier_rejects_regex() { + let error = command( + json!({"query":"foo(?:-bar)?","regex":true,"wholeIdentifier":true}), + Some("foo-barSuffix"), + ) + .unwrap_err(); + assert_eq!( + error.details.as_deref(), + Some("regex_with_whole_identifier") + ); + } + #[test] fn invalid_regex_is_reported_without_echoing_document_or_pattern() { let err = command(json!({"query":"private[", "regex":true}), Some("secret")).unwrap_err(); diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index 9321a228..3a50c29a 100644 --- a/rust/fixtures/editor/ide-essentials-v1.json +++ b/rust/fixtures/editor/ide-essentials-v1.json @@ -1,6 +1,50 @@ { "version": 1, "cases": [ + { + "name": "whole-identifier-rejects-regex", + "command": "editor.find", + "document": "foo-barSuffix", + "payload": { + "query": "foo(?:-bar)?", + "regex": true, + "wholeIdentifier": true + }, + "errorCode": "invalid_request", + "errorDetails": "regex_with_whole_identifier" + }, + { + "name": "whole-identifier-with-dollar", + "command": "editor.find", + "document": "$name $$name $nameSuffix name $name", + "payload": { + "query": "$name", + "caseSensitive": true, + "wholeIdentifier": true + }, + "expected": { + "matches": [{"start": 0, "end": 5}, {"start": 30, "end": 35}], + "edits": [], + "selected": 0, + "truncated": false + } + }, + { + "name": "whole-identifier-with-unicode-continuation", + "command": "editor.find", + "document": "foo ℘foo a·b ℘foo a·b b foo", + "payload": { + "query": "foo", + "caseSensitive": true, + "wholeIdentifier": true + }, + "expected": { + "matches": [{"start": 0, "end": 3}, {"start": 30, "end": 33}], + "edits": [], + "selected": 0, + "truncated": false + } + }, { "name": "unicode-original-byte-offsets", "command": "editor.find", From a3dbe3de380ec2ee65698d543fd1091964c1a5e4 Mon Sep 17 00:00:00 2001 From: mirakyux Date: Wed, 25 Nov 2026 21:26:50 +0800 Subject: [PATCH 4/6] style(editor): format rainbow bracket imports --- rust/crates/editor/src/rainbow_brackets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/crates/editor/src/rainbow_brackets.rs b/rust/crates/editor/src/rainbow_brackets.rs index bd3f6628..4422f1d2 100644 --- a/rust/crates/editor/src/rainbow_brackets.rs +++ b/rust/crates/editor/src/rainbow_brackets.rs @@ -2,7 +2,7 @@ use lithe_protocol::{CoreError, ErrorCode}; use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; +use serde_json::{json, Value}; /// Maximum number of bracket tokens and colors in one request. pub const MAX_BRACKETS: usize = 10_000; From 6eccef4467d4b79f17b55fcd43f8d03e69d57ba1 Mon Sep 17 00:00:00 2001 From: mirakyux Date: Thu, 26 Nov 2026 08:19:02 +0800 Subject: [PATCH 5/6] fix(editor): address rainbow feature review feedback --- rust/contracts/rust-core-api.md | 66 ++++++--- .../core/src/runtime/dispatcher/editor.rs | 22 ++- rust/crates/core/src/tests/editor_dispatch.rs | 35 +++++ .../diagnostics/src/catalog_generated.rs | 13 ++ rust/crates/editor/src/find.rs | 140 +++++++++++++++--- rust/crates/editor/src/preferences.rs | 102 +++++++++---- rust/crates/editor/src/rainbow_brackets.rs | 76 ++++++++-- rust/crates/editor/src/rainbow_variables.rs | 32 +++- rust/crates/lsp-client/src/client/results.rs | 66 +++++++-- rust/crates/lsp-engine/src/tests.rs | 2 +- rust/fixtures/editor/ide-essentials-v1.json | 8 +- rust/fixtures/editor/rainbow-brackets-v1.json | 8 +- .../fixtures/editor/rainbow-variables-v1.json | 10 +- rust/fixtures/lsp/document-highlight-v1.json | 5 +- rust/logging/events/editor.json | 20 +++ 15 files changed, 492 insertions(+), 113 deletions(-) diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index eedec8d3..6e499b45 100644 --- a/rust/contracts/rust-core-api.md +++ b/rust/contracts/rust-core-api.md @@ -3662,10 +3662,17 @@ the operation-specific URI, position, range, diagnostics, item, action, hint, or command fields, and returns `{ operationId }`. Supported operations include completion and resolve, hover, signature help (`signatureHelp`), definition/declaration/type-definition, references, implementation, rename, formatting, range formatting, document symbols, code actions and resolve, execute command, -inlay hints and resolve (`inlayHints`, `resolveInlayHint`), full-document semantic tokens, folding ranges, document links +inlay hints and resolve (`inlayHints`, `resolveInlayHint`), document highlights +(`documentHighlight`, result `{ ranges: [{ start, end, kind? }], truncated }`), +full-document semantic tokens, folding ranges, document links (`documentLinks`, result `{ links: [{ range, target, tooltip }] }`; `target` is null until a server supplies it, and entries without a range are dropped), workspace symbols (`workspaceSymbols`, see below), code lens, and provider virtual documents. +Document highlight ranges preserve the optional LSP kind (`1` Text, `2` Read, +`3` Write); an absent or invalid kind is omitted. Positions use zero-based +`line` / `utf16Column`. Nonempty, valid ranges are retained in server order, +with at most 4096 returned; `truncated` is true when another valid range was +omitted. A null result returns `{ ranges: [], truncated: false }`. For code actions, `diagnostics` contains the original `LspClientDiagnostic` objects returned by Core: nullable integer `severity`, `tags`, and `relatedInformation` remain intact, and every range uses zero-based `line` / @@ -6811,10 +6818,13 @@ Operation `documentHighlight` (`textDocument/documentHighlight`) takes a document `uri` and a zero-based `position` with a UTF-16 column. Core advertises dynamic registration. The operation is offered when the server declares `documentHighlightProvider` or dynamically registers the method. The asynchronous -completion carries `{ ranges: LspRange[] }` for occurrences in that document. +completion carries `{ ranges: [{ start, end, kind? }], truncated }` for occurrences in that document. Ranges use `line` and `utf16Column` and retain server order, up to 4096 valid nonempty ranges. Invalid entries are dropped, and a null or non-array result -returns an empty array. Core omits the optional server highlight kind. +returns `{ ranges: [], truncated: false }`. Core retains valid optional server +highlight kinds (`1` Text, `2` Read, `3` Write); absent or invalid kinds are +omitted. `truncated` is true only when another valid nonempty range exceeded +the 4096-entry budget. Fixture: `rust/fixtures/lsp/document-highlight-v1.json`. Completion requests accept optional `completionContext` with LSP `triggerKind` @@ -8601,9 +8611,15 @@ All offsets are original UTF-8 byte offsets, half-open and on rune boundaries. A range searches the whole snapshot. Regex uses Unicode case folding/word boundaries and multiline anchors; regex replacement expands `$1`/`${name}` captures; literal replacement preserves dollar signs. `replaceStart` selects only that match; omitted means replace all. -For literal searches, `wholeIdentifier` checks both ends of a match against Unicode -`ID_Continue`, join controls and `$`, including adjacent characters outside a -scoped search. It takes precedence over `wholeWord`. Setting both +For literal searches, `wholeIdentifier` checks an edge only when that edge of +the match is itself Unicode `ID_Continue`, a join control or `$`; it must not +touch another identifier continuation, including outside a scoped search. +Punctuation edges may touch any character. A rejected candidate resumes after +its initial identifier run (or one character after a punctuation start), so an +overlapping valid match is retained. Rejected candidates that rescan bytes are +limited to 100,000 retries and then report `truncated: true`; pure identifier +queries skip each run in linear time without spending that retry budget. +It takes precedence over `wholeWord`. Setting both `wholeIdentifier` and `regex` to true returns `invalid_request` with `regex_with_whole_identifier` in the details. Results are `{matches:[{start,end}],edits:[{start,end,text}],selected:number|null,truncated}`. @@ -8620,11 +8636,15 @@ Source, query and replacement are never included in errors or diagnostic logs. `editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`, `indentGuides`, `rainbowIndentGuides`, `cursorStyle` (`line`, `block`, `underline`), `cursorBlink`, `autoSaveDelayMilliseconds`, -`rainbowBrackets`, `rainbowVariables`, `rainbowBracketLightColors` and -`rainbowBracketDarkColors`. -It returns actual values and minimum/maximum delay. Defaults: true, false, true, line, -true, 1500 ms; unknown styles resolve to line and delay clamps to 250–60,000 ms. -Indent guides default to enabled and rainbow indent guides default to disabled. +`rainbowBrackets`, `rainbowVariables`, `rainbowLightColors` and +`rainbowDarkColors`. +It returns actual values and minimum/maximum delay. Defaults by field: +`lineNumbers: true`, `whitespace: false`, `indentGuides: true`, +`rainbowIndentGuides: false`, `inlayHints: true`, `cursorStyle: "line"`, +`cursorBlink: true`, `autoSaveDelayMilliseconds: 1500`, `rainbowBrackets: false` +and `rainbowVariables: false`. Unknown styles resolve to line and delay clamps +to 250–60,000 ms. Unknown stored fields are ignored so a newer client's +preferences do not discard known choices when read by an older client. The result returns both choices independently and adds `rainbowIndentGuidesEffective`, which is true when both choices are enabled. Rainbow brackets and variable coloring are independent options that default to @@ -8632,9 +8652,13 @@ disabled and share the light and dark palettes. Each palette accepts one to eigh `#RRGGBB` strings with optional surrounding whitespace and case-insensitive ASCII hex. Core returns uppercase values. An absent, empty or malformed palette uses the default palette for that theme, independently of the other theme. +An explicitly malformed palette records the WARN catalog fact +`editor.preferences.palette_fallback_selected`, with only `palette: light|dark` +and `reason: invalid_palette`; absence uses the normal default without a warning. `editor.rainbowBrackets` accepts `{brackets:[{offset,bracket}]}` and returns -`{colors:[{offset,depth,matchOffset?}]}` in input order. Offsets are zero-based UTF-8 byte +`{colors:[{offset,depth,matchOffset?}]}` in input order, omitting unmatched closers. +Offsets are zero-based UTF-8 byte positions and must increase strictly. The offset and the exclusive end of its one-byte range must fit an unsigned 32-bit integer. Allowed tokens are `()[]{}`, with at most 10,000 tokens per request. The host supplies tokens from its @@ -8642,9 +8666,14 @@ language tokenizer and omits tokens in comments or literals. Each opener is colored by its zero-based nesting depth, and a matching closer uses the same depth. Both ends of a matched pair include the other end's byte offset as `matchOffset`. An unmatched opener keeps its color and has no `matchOffset`. -An unmatched or mismatched closer keeps its base color and leaves open pairs -intact. Core returns `invalid_request` for invalid token data or offsets -and for requests that exceed the token limit. +A closer pairs with the innermost opener of its kind. Intervening unclosed +openers are removed from the active stack but retain their original depth and +have no match; subsequent pairs resume at the recovered nesting depth. A closer +with no opener of its kind is omitted. Kind counts avoid searching unmatched +stacks and each opener is removed at most once, so recovery is O(n). +Core returns `invalid_request` for invalid token data or offsets and for +requests that exceed the token limit. Executable vectors: +`rust/fixtures/editor/rainbow-brackets-v1.json` (JSON dispatcher tests). `editor.rainbowVariables` accepts `{variables:[{start,end,name}]}` and returns `{colors:[{start,end,color}]}` in input order. The host supplies variable tokens @@ -8653,9 +8682,12 @@ are unsigned 32-bit UTF-8 byte offsets forming a nonempty half-open range. The ranges must be in document order and must not overlap. A request is limited to 10,000 ranges. Each name must contain 1–256 UTF-8 bytes and match the length of its range. Core computes `color` as unsigned 32-bit FNV-1a over the exact name -bytes, preserving case. A host takes the result modulo the active palette +bytes, preserving case, followed by Murmur3 fmix32: XOR-shift 16, multiply by +`0x85EBCA6B`, XOR-shift 13, multiply by `0xC2B2AE35`, then XOR-shift 16 (all +multiplication wraps to 32 bits). A host takes the result modulo the active palette length. Core returns `invalid_request` for malformed requests and bounds -violations. +violations. Executable vectors: `rust/fixtures/editor/rainbow-variables-v1.json` +(JSON dispatcher tests). `editor.recent.reduce` accepts `entries`, optional `event:{kind,path,name,line,column}`, `query` and `onlyEdited`. It returns bounded `entries` and filtered `results`. Paths are diff --git a/rust/crates/core/src/runtime/dispatcher/editor.rs b/rust/crates/core/src/runtime/dispatcher/editor.rs index a4681ae0..432bb070 100644 --- a/rust/crates/core/src/runtime/dispatcher/editor.rs +++ b/rust/crates/core/src/runtime/dispatcher/editor.rs @@ -4,6 +4,8 @@ use super::{plugin_response, rules_response}; use crate::protocol::{CoreError, CoreResponse, EditorCommand, ErrorCode}; use serde_json::Value; +const PALETTE_FALLBACK_EVENT: &str = "editor.preferences.palette_fallback_selected"; + /// Runs one `editor.*` command. pub(super) fn dispatch( command: EditorCommand, @@ -30,9 +32,23 @@ pub(super) fn dispatch( Ok(data) => CoreResponse::success(id, data), Err(error) => CoreResponse::failure(id, error), }, - EditorCommand::PreferencesResolve => { - plugin_response(id, payload, lithe_editor::preferences::resolve_command) - } + EditorCommand::PreferencesResolve => plugin_response(id, payload, |payload| { + lithe_editor::preferences::resolve_command_with_fallback(payload, |palette| { + let fields = std::collections::BTreeMap::from([ + ("palette".into(), serde_json::json!(palette)), + ("reason".into(), serde_json::json!("invalid_palette")), + ]); + if lithe_diagnostics::core_events::record( + PALETTE_FALLBACK_EVENT, + fields, + lithe_request_context::trace::current().op, + ) + .is_err() + { + lithe_diagnostics::core_events::note_dropped(); + } + }) + }), EditorCommand::RainbowBrackets => { plugin_response(id, payload, lithe_editor::rainbow_brackets::color_command) } diff --git a/rust/crates/core/src/tests/editor_dispatch.rs b/rust/crates/core/src/tests/editor_dispatch.rs index 07cf2867..d7b99d8f 100644 --- a/rust/crates/core/src/tests/editor_dispatch.rs +++ b/rust/crates/core/src/tests/editor_dispatch.rs @@ -3,6 +3,41 @@ use serde_json::{json, Value}; +#[test] +fn malformed_rainbow_palettes_record_a_private_fallback_fact_per_theme() { + let (response, facts) = lithe_diagnostics::core_events::capture::run(false, || { + crate::execute_json( + &json!({"command":"editor.preferences.resolve","payload":{ + "rainbowLightColors":["private-invalid-color"], + "rainbowDarkColors":[],"lineNumbers":false,"futureOption":true + }}) + .to_string(), + ) + }); + let response: Value = serde_json::from_str(&response).unwrap(); + assert_eq!(response["ok"], true); + assert_eq!(response["data"]["lineNumbers"], false); + let fallbacks: Vec<_> = facts + .iter() + .filter(|fact| fact.event == "editor.preferences.palette_fallback_selected") + .collect(); + assert_eq!(fallbacks.len(), 2); + for (fact, theme) in fallbacks.iter().zip(["light", "dark"]) { + assert_eq!(fact.level, lithe_diagnostics::record::LogLevel::Warn); + assert_eq!(fact.fields["palette"], theme); + assert_eq!(fact.fields["reason"], "invalid_palette"); + assert_eq!(fact.fields.len(), 2); + } + let (_, facts) = lithe_diagnostics::core_events::capture::run(false, || { + crate::execute_json( + &json!({"command":"editor.preferences.resolve","payload":{}}).to_string(), + ) + }); + assert!(facts + .iter() + .all(|fact| fact.event != "editor.preferences.palette_fallback_selected")); +} + #[test] fn rainbow_brackets_match_shared_fixture() { let fixture: Value = serde_json::from_str(include_str!( diff --git a/rust/crates/diagnostics/src/catalog_generated.rs b/rust/crates/diagnostics/src/catalog_generated.rs index 11e4ac3f..e7252238 100644 --- a/rust/crates/diagnostics/src/catalog_generated.rs +++ b/rust/crates/diagnostics/src/catalog_generated.rs @@ -562,6 +562,19 @@ pub static EVENTS: &[EventMetadata] = &[ rate: 60, owner: "Lithe", }, + EventMetadata { + id: "editor.preferences.palette_fallback_selected", + channel: "editor", + level: LogLevel::Warn, + message: "Invalid {palette} rainbow palette replaced with its default", + fields: &[ + FieldMetadata { name: "palette", field_type: FieldType::Token, required: true, description: "Theme of the invalid stored rainbow palette, either light or dark", reason: None }, + FieldMetadata { name: "reason", field_type: FieldType::Token, required: true, description: "Controlled fallback reason for this palette, currently invalid_palette", reason: None }, + ], + span: None, + rate: 60, + owner: "lithe-core", + }, EventMetadata { id: "editor.recovery.applied", channel: "editor", diff --git a/rust/crates/editor/src/find.rs b/rust/crates/editor/src/find.rs index 4ce56566..c63a2074 100644 --- a/rust/crates/editor/src/find.rs +++ b/rust/crates/editor/src/find.rs @@ -13,6 +13,9 @@ const MAX_SOURCE_BYTES: usize = 64 * 1024 * 1024; const MAX_QUERY_BYTES: usize = 4096; const MAX_MATCHES: usize = 10_000; const MAX_REPLACEMENT_BYTES: usize = 8 * 1024 * 1024; +/// Bound rejected candidates that rescan already-searched bytes. Identifier-only +/// queries skip each rejected identifier run once and do not spend this budget. +const MAX_IDENTIFIER_RETRIES: usize = 100_000; #[derive(Deserialize)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -63,6 +66,36 @@ fn identifier_continues(character: char) -> bool { NON_ASCII_CONTINUATION.is_match(character.encode_utf8(&mut [0; 4])) } +/// Punctuation at a match edge never joins an adjacent identifier. Only an +/// identifier character at that edge needs a boundary in the original document. +fn identifier_bounded(source: &str, at: usize, through: usize) -> bool { + let matched = &source[at..through]; + let joins = |edge: Option, beside: Option| { + edge.is_some_and(identifier_continues) && beside.is_some_and(identifier_continues) + }; + !joins(matched.chars().next(), source[..at].chars().next_back()) + && !joins( + matched.chars().next_back(), + source[through..].chars().next(), + ) +} + +/// Skip the identifier run containing the rejected start: no later start in +/// that run can have a left boundary. A punctuation start advances one rune. +fn next_identifier_candidate(text: &str, at: usize) -> usize { + for (offset, character) in text[at..].char_indices() { + if !identifier_continues(character) { + return at + + if offset == 0 { + character.len_utf8() + } else { + offset + }; + } + } + text.len() +} + /// Finds matches in the borrowed document `source` and, when a replacement is /// requested, plans the edits (`editor.find`). /// @@ -119,47 +152,67 @@ pub fn command(payload: Value, source: Option<&str>) -> Result let mut truncated = false; let mut replacement_bytes = 0; let mut removed_bytes = 0; - for captures in matcher.captures_iter(text) { - cancellation::check()?; - let m = captures - .get(0) - .expect("a successful capture has a whole match"); - let at = start + m.start(); - let through = start + m.end(); - if request.whole_identifier - && (source[..at] - .chars() - .next_back() - .is_some_and(identifier_continues) - || source[through..] - .chars() - .next() - .is_some_and(identifier_continues)) - { - continue; - } + let mut record = |at: usize, + through: usize, + captures: Option<®ex::Captures<'_>>| + -> Result { if matches.len() == MAX_MATCHES { - truncated = true; - break; + return Ok(false); } matches.push(json!({"start":at, "end":through})); if let Some(replacement) = &request.replacement { if request.replace_start.is_some_and(|wanted| wanted != at) { - continue; + return Ok(true); } let mut inserted = String::new(); - if request.regex { + if let Some(captures) = captures.filter(|_| request.regex) { captures.expand(replacement, &mut inserted); } else { inserted.push_str(replacement); } replacement_bytes += inserted.len(); - removed_bytes += m.len(); + removed_bytes += through - at; if replacement_bytes > MAX_REPLACEMENT_BYTES { return Err(invalid("replacement_too_large")); } edits.push(json!({"start":at, "end":through, "text":inserted})); } + Ok(true) + }; + if request.whole_identifier { + let mut from = 0; + let mut retries = 0; + while let Some(m) = matcher.find_at(text, from) { + cancellation::check()?; + let (at, through) = (start + m.start(), start + m.end()); + if identifier_bounded(source, at, through) { + if !record(at, through, None)? { + truncated = true; + break; + } + from = m.end(); + continue; + } + from = next_identifier_candidate(text, m.start()); + if from < m.end() { + retries += 1; + if retries > MAX_IDENTIFIER_RETRIES { + truncated = true; + break; + } + } + } + } else { + for captures in matcher.captures_iter(text) { + cancellation::check()?; + let m = captures + .get(0) + .expect("a successful capture has a whole match"); + if !record(start + m.start(), start + m.end(), Some(&captures))? { + truncated = true; + break; + } + } } if truncated && request.replacement.is_some() && request.replace_start.is_none() { return Err(invalid("too_many_matches")); @@ -187,6 +240,45 @@ pub fn command(payload: Value, source: Option<&str>) -> Result mod tests { use super::*; + #[test] + fn whole_identifier_retries_overlapping_candidates_and_respects_punctuation_edges() { + for (query, source, expected) in [ + ("a-a", "xa-a-a", json!([{"start":3,"end":6}])), + ("obj.obj", "aobj.obj.obj", json!([{"start":5,"end":12}])), + ("ab", "abab ab", json!([{"start":5,"end":7}])), + ("(foo", "x(foo", json!([{"start":1,"end":5}])), + ("foo(", "call foo(bar)", json!([{"start":5,"end":9}])), + (".x", "a.x", json!([{"start":1,"end":3}])), + ] { + let result = + command(json!({"query":query,"wholeIdentifier":true}), Some(source)).unwrap(); + assert_eq!(result["matches"], expected, "query {query}"); + assert_eq!(result["truncated"], false); + } + } + + #[test] + fn whole_identifier_skips_identifier_runs_without_spending_retry_budget() { + let source = format!("{} a", "a".repeat(400_000)); + let result = command(json!({"query":"a","wholeIdentifier":true}), Some(&source)).unwrap(); + assert_eq!(result["matches"], json!([{"start":400001,"end":400002}])); + assert_eq!(result["truncated"], false); + } + + #[test] + fn whole_identifier_bounds_repeated_candidate_rescans_and_rejects_partial_bulk_edits() { + let source = "xa-a ".repeat(100_001); + let result = command(json!({"query":"a-a","wholeIdentifier":true}), Some(&source)).unwrap(); + assert_eq!(result["matches"], json!([])); + assert_eq!(result["truncated"], true); + let error = command( + json!({"query":"a-a","wholeIdentifier":true,"replacement":"b"}), + Some(&source), + ) + .unwrap_err(); + assert_eq!(error.details.as_deref(), Some("too_many_matches")); + } + #[test] fn unicode_case_folding_preserves_original_byte_offsets() { let result = command(json!({"query":"k", "caret":2}), Some("😀Kk")).unwrap(); diff --git a/rust/crates/editor/src/preferences.rs b/rust/crates/editor/src/preferences.rs index d790a53f..b7b0da98 100644 --- a/rust/crates/editor/src/preferences.rs +++ b/rust/crates/editor/src/preferences.rs @@ -5,15 +5,15 @@ use serde::Deserialize; use serde_json::{json, Value}; const MAX_RAINBOW_COLORS: usize = 8; -const LIGHT_BRACKET_COLORS: &[&str] = &[ +const LIGHT_RAINBOW_COLORS: &[&str] = &[ "#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68", ]; -const DARK_BRACKET_COLORS: &[&str] = &[ +const DARK_RAINBOW_COLORS: &[&str] = &[ "#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4", ]; #[derive(Default, Deserialize)] -#[serde(rename_all = "camelCase", deny_unknown_fields)] +#[serde(rename_all = "camelCase")] struct Stored { line_numbers: Option, whitespace: Option, @@ -27,16 +27,37 @@ struct Stored { rainbow_variables: Option, // Retain each raw palette independently so a malformed color can fall // back without discarding the other persisted preferences. - rainbow_bracket_light_colors: Option, - rainbow_bracket_dark_colors: Option, + #[serde(default, deserialize_with = "retain_palette")] + rainbow_light_colors: Option, + #[serde(default, deserialize_with = "retain_palette")] + rainbow_dark_colors: Option, } -fn effective_palette(stored: Option<&Value>, defaults: &[&str]) -> Vec { - stored +// Explicit null is a malformed stored palette; only an absent field is an +// ordinary default. Option's default decoder would erase that distinction. +fn retain_palette<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> Result, D::Error> { + Value::deserialize(deserializer).map(Some) +} + +fn effective_palette( + stored: Option<&Value>, + defaults: &[&str], + theme: &'static str, + on_fallback: &mut impl FnMut(&'static str), +) -> Vec { + let normalized = stored .and_then(Value::as_array) .filter(|colors| (1..=MAX_RAINBOW_COLORS).contains(&colors.len())) - .and_then(|colors| colors.iter().map(normalize_color).collect()) - .unwrap_or_else(|| defaults.iter().map(|color| (*color).to_owned()).collect()) + .and_then(|colors| colors.iter().map(normalize_color).collect()); + if let Some(colors) = normalized { + return colors; + } + if stored.is_some() { + on_fallback(theme); + } + defaults.iter().map(|color| (*color).to_owned()).collect() } fn normalize_color(value: &Value) -> Option { @@ -50,6 +71,16 @@ fn normalize_color(value: &Value) -> Option { /// defaults, normalizing rainbow palettes and clamping the auto-save delay /// (`editor.preferences.resolve`). pub fn resolve_command(payload: Value) -> Result { + resolve_command_with_fallback(payload, |_| {}) +} + +/// Resolves preferences and reports each malformed stored palette to the owning +/// runtime's diagnostic sink. The callback receives only the fixed theme token, +/// never a color value; absent palettes are normal defaults and emit no fact. +pub fn resolve_command_with_fallback( + payload: Value, + mut on_fallback: impl FnMut(&'static str), +) -> Result { let stored: Stored = serde_json::from_value(payload) .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid editor preferences"))?; let style = match stored.cursor_style.as_deref() { @@ -73,14 +104,38 @@ pub fn resolve_command(payload: Value) -> Result { "maximumAutoSaveDelayMilliseconds":60_000, "rainbowBrackets":stored.rainbow_brackets.unwrap_or(false), "rainbowVariables":stored.rainbow_variables.unwrap_or(false), - "rainbowBracketLightColors":effective_palette(stored.rainbow_bracket_light_colors.as_ref(), LIGHT_BRACKET_COLORS), - "rainbowBracketDarkColors":effective_palette(stored.rainbow_bracket_dark_colors.as_ref(), DARK_BRACKET_COLORS) + "rainbowLightColors":effective_palette(stored.rainbow_light_colors.as_ref(), LIGHT_RAINBOW_COLORS, "light", &mut on_fallback), + "rainbowDarkColors":effective_palette(stored.rainbow_dark_colors.as_ref(), DARK_RAINBOW_COLORS, "dark", &mut on_fallback) })) } #[cfg(test)] mod tests { use super::*; + + #[test] + fn future_preferences_do_not_discard_known_stored_choices() { + let value = + resolve_command(json!({"lineNumbers":false,"futureOption":{"enabled":true}})).unwrap(); + assert_eq!(value["lineNumbers"], false); + } + + #[test] + fn palette_fallback_observer_reports_explicit_null_but_not_absence_or_valid_palettes() { + let mut fallbacks = Vec::new(); + let result = resolve_command_with_fallback( + json!({ + "rainbowLightColors":null,"rainbowDarkColors":["#abcdef"] + }), + |theme| fallbacks.push(theme), + ) + .unwrap(); + assert_eq!(fallbacks, ["light"]); + assert_eq!(result["rainbowDarkColors"], json!(["#ABCDEF"])); + fallbacks.clear(); + resolve_command_with_fallback(json!({}), |theme| fallbacks.push(theme)).unwrap(); + assert!(fallbacks.is_empty()); + } #[test] fn missing_and_old_preferences_get_the_existing_editor_defaults() { let value = resolve_command(json!({})).unwrap(); @@ -95,14 +150,8 @@ mod tests { assert_eq!(value["autoSaveDelayMilliseconds"], 1500); assert_eq!(value["rainbowBrackets"], false); assert_eq!(value["rainbowVariables"], false); - assert_eq!( - value["rainbowBracketLightColors"], - json!(LIGHT_BRACKET_COLORS) - ); - assert_eq!( - value["rainbowBracketDarkColors"], - json!(DARK_BRACKET_COLORS) - ); + assert_eq!(value["rainbowLightColors"], json!(LIGHT_RAINBOW_COLORS)); + assert_eq!(value["rainbowDarkColors"], json!(DARK_RAINBOW_COLORS)); } #[test] fn rainbow_indent_guides_keep_the_choice_when_guides_are_hidden() { @@ -131,6 +180,7 @@ mod tests { #[test] fn rainbow_palettes_normalize_and_fall_back_independently() { for bad_palette in [ + Value::Null, json!([]), json!(["#GG0000"]), json!(["#123456", 0]), @@ -141,21 +191,15 @@ mod tests { "lineNumbers": false, "rainbowBrackets": true, "rainbowVariables": true, - "rainbowBracketLightColors": bad_palette, - "rainbowBracketDarkColors": [" #aabbcc ", "#D3D3D3"], + "rainbowLightColors": bad_palette, + "rainbowDarkColors": [" #aabbcc ", "#D3D3D3"], })) .unwrap(); assert_eq!(value["lineNumbers"], false); assert_eq!(value["rainbowBrackets"], true); assert_eq!(value["rainbowVariables"], true); - assert_eq!( - value["rainbowBracketLightColors"], - json!(LIGHT_BRACKET_COLORS) - ); - assert_eq!( - value["rainbowBracketDarkColors"], - json!(["#AABBCC", "#D3D3D3"]) - ); + assert_eq!(value["rainbowLightColors"], json!(LIGHT_RAINBOW_COLORS)); + assert_eq!(value["rainbowDarkColors"], json!(["#AABBCC", "#D3D3D3"])); } } } diff --git a/rust/crates/editor/src/rainbow_brackets.rs b/rust/crates/editor/src/rainbow_brackets.rs index 4422f1d2..7516e8d5 100644 --- a/rust/crates/editor/src/rainbow_brackets.rs +++ b/rust/crates/editor/src/rainbow_brackets.rs @@ -24,6 +24,14 @@ enum Bracket { } impl Bracket { + fn kind(self) -> usize { + match self { + Self::OpenParen | Self::CloseParen => 0, + Self::OpenSquare | Self::CloseSquare => 1, + Self::OpenBrace | Self::CloseBrace => 2, + } + } + fn closing(self) -> Option { match self { Self::OpenParen => Some(Self::CloseParen), @@ -61,8 +69,9 @@ struct Color { } /// Returns both endpoints of each matched pair at the same nesting depth. -/// A mismatched closer is omitted and leaves the stack available for a later -/// match. Openers retain their current depth while the document is incomplete. +/// A closer pairs with the innermost opener of its kind, discarding intervening +/// unclosed openers from the active stack. Discarded openers retain their color +/// without a match; a closer with no opener of its kind is omitted. pub fn color_command(payload: Value) -> Result { let request: Request = serde_json::from_value(payload) .map_err(|_| CoreError::new(ErrorCode::InvalidRequest, "Invalid rainbow bracket tokens"))?; @@ -74,7 +83,9 @@ pub fn color_command(payload: Value) -> Result { } let mut previous_offset = None; - let mut expected_closers = Vec::new(); + let mut open = Vec::new(); + let mut open_by_kind = [0_usize; 3]; + let mut kinds = Vec::with_capacity(request.brackets.len()); let mut colors: Vec = Vec::with_capacity(request.brackets.len()); for token in request.brackets { // The host uses a one-byte range, so its exclusive end must fit too. @@ -87,20 +98,27 @@ pub fn color_command(payload: Value) -> Result { } previous_offset = Some(token.offset); - let (depth, match_offset) = if let Some(closing) = token.bracket.closing() { - let depth = expected_closers.len(); - expected_closers.push((closing, colors.len())); - (depth, None) - } else if let Some(&(_, opener)) = expected_closers - .last() - .filter(|(closing, _)| *closing == token.bracket) - { - expected_closers.pop(); + let kind = token.bracket.kind(); + let (depth, match_offset) = if token.bracket.closing().is_some() { + open.push(colors.len()); + open_by_kind[kind] += 1; + (open.len() - 1, None) + } else if open_by_kind[kind] > 0 { + // Counts avoid searching an unmatched stack. Each opener is popped + // at most once, so malformed edits retain the linear token budget. + let opener = loop { + let innermost = open.pop().expect("an opener of this kind remains"); + open_by_kind[kinds[innermost]] -= 1; + if kinds[innermost] == kind { + break innermost; + } + }; colors[opener].match_offset = Some(token.offset); - (expected_closers.len(), Some(colors[opener].offset)) + (open.len(), Some(colors[opener].offset)) } else { continue; }; + kinds.push(kind); colors.push(Color { offset: token.offset, depth: depth as u32, @@ -114,6 +132,38 @@ pub fn color_command(payload: Value) -> Result { mod tests { use super::*; + #[test] + fn mismatched_inner_openers_do_not_leak_depth_into_later_pairs() { + let result = color_command(json!({"brackets":[ + {"offset":0,"bracket":"{"}, {"offset":5,"bracket":"("}, + {"offset":7,"bracket":"}"}, {"offset":9,"bracket":"("}, + {"offset":10,"bracket":")"} + ]})) + .unwrap(); + assert_eq!( + result["colors"], + json!([ + {"offset":0,"depth":0,"matchOffset":7}, {"offset":5,"depth":1}, + {"offset":7,"depth":0,"matchOffset":0}, {"offset":9,"depth":0,"matchOffset":10}, + {"offset":10,"depth":0,"matchOffset":9} + ]) + ); + } + + #[test] + fn repeated_missing_closers_leave_deep_openers_for_the_matching_kind() { + let mut brackets: Vec = (0..5000) + .map(|offset| json!({"offset":offset,"bracket":"("})) + .collect(); + brackets.extend((5000..9999).map(|offset| json!({"offset":offset,"bracket":"]"}))); + brackets.push(json!({"offset":9999,"bracket":")"})); + let result = color_command(json!({"brackets":brackets})).unwrap(); + let colors = result["colors"].as_array().unwrap(); + assert_eq!(colors.len(), 5001); + assert_eq!(colors[4999]["matchOffset"], 9999); + assert_eq!(colors[5000]["depth"], 4999); + } + #[test] fn accepts_the_token_limit_and_rejects_the_next_token() { let mut brackets: Vec = (0..MAX_BRACKETS) diff --git a/rust/crates/editor/src/rainbow_variables.rs b/rust/crates/editor/src/rainbow_variables.rs index 0914bab5..d9efd55e 100644 --- a/rust/crates/editor/src/rainbow_variables.rs +++ b/rust/crates/editor/src/rainbow_variables.rs @@ -80,13 +80,41 @@ fn name_color(name: &str) -> u32 { hash ^= u32::from(byte); hash = hash.wrapping_mul(0x0100_0193); } - hash + // Murmur3 fmix32 diffuses the low bits before the host takes a palette + // modulus, so similar spellings do not systematically share a slot. + hash ^= hash >> 16; + hash = hash.wrapping_mul(0x85eb_ca6b); + hash ^= hash >> 13; + hash = hash.wrapping_mul(0xc2b2_ae35); + hash ^ (hash >> 16) } #[cfg(test)] mod tests { use super::*; + #[test] + fn similar_names_distribute_across_eight_color_slots() { + let names = ["user1", "user9", "a", "i", "arg0", "arg8", "x", "p"]; + let colors = names.map(name_color); + assert_eq!( + colors, + [ + 3_385_640_019, + 1_105_349_995, + 444_641_715, + 1_311_273_838, + 2_657_546_199, + 1_664_241_451, + 794_621_484, + 2_710_276_834 + ] + ); + let slots: std::collections::BTreeSet<_> = + colors.map(|color| color % 8).into_iter().collect(); + assert!(slots.len() >= 5, "similar spellings use {slots:?}"); + } + #[test] fn enforces_token_and_name_budgets() { let mut variables: Vec = (0..MAX_VARIABLES) @@ -95,7 +123,7 @@ mod tests { let result = color_command(json!({"variables":&variables})).unwrap(); let colors = result["colors"].as_array().unwrap(); assert_eq!(colors.len(), MAX_VARIABLES); - assert_eq!(colors[MAX_VARIABLES - 1]["color"], 3_826_002_220_u32); + assert_eq!(colors[MAX_VARIABLES - 1]["color"], 444_641_715_u32); variables.push(json!({"start":MAX_VARIABLES,"end":MAX_VARIABLES+1,"name":"a"})); let error = color_command(json!({"variables":variables})).unwrap_err(); diff --git a/rust/crates/lsp-client/src/client/results.rs b/rust/crates/lsp-client/src/client/results.rs index f88ee6b4..1637ced5 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -39,9 +39,7 @@ pub(crate) fn lsp_feature_result_for_method( Some("textDocument/documentSymbol") => Some(json!({ "symbols": parse_document_symbols(result) })), - Some("textDocument/documentHighlight") => Some(json!({ - "ranges": parse_document_highlights(result) - })), + Some("textDocument/documentHighlight") => Some(parse_document_highlights(result)), Some("textDocument/inlayHint") => Some(json!({ "hints": parse_inlay_hints(result) })), @@ -717,9 +715,9 @@ fn parse_document_symbol(item: &Value) -> Option { } /// Retains only nonempty, ordered ranges and bounds the payload sent to the editor. -fn parse_document_highlights(result: &Value) -> Vec { +fn parse_document_highlights(result: &Value) -> Value { const MAX_HIGHLIGHTS: usize = 4096; - result + let mut highlights = result .as_array() .into_iter() .flatten() @@ -727,10 +725,22 @@ fn parse_document_highlights(result: &Value) -> Vec { let range = parse_lsp_range(highlight.get("range")?)?; let start = (range.start.line, range.start.utf16_column); let end = (range.end.line, range.end.utf16_column); - (start.0 >= 0 && start.1 >= 0 && end.1 >= 0 && start < end).then_some(range) - }) - .take(MAX_HIGHLIGHTS) - .collect() + if start.0 < 0 || start.1 < 0 || end.1 < 0 || start >= end { + return None; + } + let mut value = json!(range); + if let Some(kind) = highlight + .get("kind") + .and_then(Value::as_u64) + .filter(|kind| (1..=3).contains(kind)) + { + value["kind"] = json!(kind); + } + Some(value) + }); + let ranges: Vec<_> = highlights.by_ref().take(MAX_HIGHLIGHTS).collect(); + let truncated = highlights.next().is_some(); + json!({"ranges":ranges, "truncated":truncated}) } fn parse_folding_ranges(result: &Value) -> Vec { @@ -1048,3 +1058,41 @@ fn parse_lsp_position_value(value: &Value) -> Option { .unwrap_or(0) })) } + +#[cfg(test)] +mod highlight_tests { + use super::*; + + #[test] + fn document_highlights_keep_optional_kinds_and_report_only_valid_range_truncation() { + let entry = |kind: Value| json!({"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}},"kind":kind}); + let result = lsp_feature_result_for_method( + Some("textDocument/documentHighlight"), + Some(&json!([ + entry(json!(1)), + entry(json!(2)), + entry(json!(3)), + entry(json!(9)) + ])), + &BTreeMap::new(), + ) + .unwrap(); + assert_eq!(result["truncated"], false); + for index in 0..3 { + assert_eq!(result["ranges"][index]["kind"], index + 1); + } + assert!(result["ranges"][3].get("kind").is_none()); + for (count, truncated) in [(4096, false), (4097, true)] { + let mut entries = vec![entry(json!(3)); count]; + entries.insert(0, json!({"kind":1})); + let value = lsp_feature_result_for_method( + Some("textDocument/documentHighlight"), + Some(&json!(entries)), + &BTreeMap::new(), + ) + .unwrap(); + assert_eq!(value["ranges"].as_array().unwrap().len(), 4096); + assert_eq!(value["truncated"], truncated); + } + } +} diff --git a/rust/crates/lsp-engine/src/tests.rs b/rust/crates/lsp-engine/src/tests.rs index cde0d667..089efd90 100644 --- a/rust/crates/lsp-engine/src/tests.rs +++ b/rust/crates/lsp-engine/src/tests.rs @@ -2281,7 +2281,7 @@ fn document_highlight_routes_and_normalizes_document_ranges() { let column = fixture["position"]["utf16Column"].as_i64().unwrap(); for (index, (server_result, expected)) in [ (fixture["serverResult"].clone(), fixture["expected"].clone()), - (Value::Null, json!({"ranges": []})), + (Value::Null, json!({"ranges": [], "truncated": false})), ] .into_iter() .enumerate() diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index 3a50c29a..6839339a 100644 --- a/rust/fixtures/editor/ide-essentials-v1.json +++ b/rust/fixtures/editor/ide-essentials-v1.json @@ -113,8 +113,8 @@ "maximumAutoSaveDelayMilliseconds": 60000, "rainbowBrackets": false, "rainbowVariables": false, - "rainbowBracketLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], - "rainbowBracketDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] + "rainbowLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], + "rainbowDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] } }, { @@ -138,8 +138,8 @@ "maximumAutoSaveDelayMilliseconds": 60000, "rainbowBrackets": false, "rainbowVariables": false, - "rainbowBracketLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], - "rainbowBracketDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] + "rainbowLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], + "rainbowDarkColors": ["#FF8A80", "#82B1FF", "#D7A9FF", "#5CE1C4", "#FFBF69", "#A6B8D4"] } }, { diff --git a/rust/fixtures/editor/rainbow-brackets-v1.json b/rust/fixtures/editor/rainbow-brackets-v1.json index a6db6d90..b588ba3d 100644 --- a/rust/fixtures/editor/rainbow-brackets-v1.json +++ b/rust/fixtures/editor/rainbow-brackets-v1.json @@ -44,10 +44,10 @@ }, "expected": { "colors": [ - { "offset": 2, "depth": 0 }, - { "offset": 3, "depth": 1, "matchOffset": 5 }, - { "offset": 5, "depth": 1, "matchOffset": 3 }, - { "offset": 6, "depth": 1 } + { "offset": 2, "depth": 0, "matchOffset": 4 }, + { "offset": 3, "depth": 1 }, + { "offset": 4, "depth": 0, "matchOffset": 2 }, + { "offset": 6, "depth": 0 } ] } }, diff --git a/rust/fixtures/editor/rainbow-variables-v1.json b/rust/fixtures/editor/rainbow-variables-v1.json index 5e32ccd0..eab282a6 100644 --- a/rust/fixtures/editor/rainbow-variables-v1.json +++ b/rust/fixtures/editor/rainbow-variables-v1.json @@ -17,11 +17,11 @@ }, "expected": { "colors": [ - { "start": 0, "end": 5, "color": 1113510858 }, - { "start": 7, "end": 12, "color": 3363671541 }, - { "start": 13, "end": 18, "color": 1113510858 }, - { "start": 18, "end": 23, "color": 3511155050 }, - { "start": 25, "end": 31, "color": 4246680784 } + { "start": 0, "end": 5, "color": 1743838389 }, + { "start": 7, "end": 12, "color": 3468624197 }, + { "start": 13, "end": 18, "color": 1743838389 }, + { "start": 18, "end": 23, "color": 1520666834 }, + { "start": 25, "end": 31, "color": 3554379875 } ] } }, diff --git a/rust/fixtures/lsp/document-highlight-v1.json b/rust/fixtures/lsp/document-highlight-v1.json index b1458c23..2a0db0b9 100644 --- a/rust/fixtures/lsp/document-highlight-v1.json +++ b/rust/fixtures/lsp/document-highlight-v1.json @@ -13,8 +13,9 @@ ], "expected": { "ranges": [ - {"start": {"line": 1, "utf16Column": 7}, "end": {"line": 1, "utf16Column": 11}}, + {"start": {"line": 1, "utf16Column": 7}, "end": {"line": 1, "utf16Column": 11}, "kind": 3}, {"start": {"line": 2, "utf16Column": 15}, "end": {"line": 2, "utf16Column": 19}} - ] + ], + "truncated": false } } diff --git a/rust/logging/events/editor.json b/rust/logging/events/editor.json index d749e392..60df805f 100644 --- a/rust/logging/events/editor.json +++ b/rust/logging/events/editor.json @@ -163,6 +163,26 @@ "fields": {}, "rate": 60, "owner": "Lithe" + }, + { + "id": "editor.preferences.palette_fallback_selected", + "channel": "editor", + "level": "warn", + "message": "Invalid {palette} rainbow palette replaced with its default", + "fields": { + "palette": { + "type": "token", + "required": true, + "description": "Theme of the invalid stored rainbow palette, either light or dark" + }, + "reason": { + "type": "token", + "required": true, + "description": "Controlled fallback reason for this palette, currently invalid_palette" + } + }, + "rate": 60, + "owner": "lithe-core" } ] } From 4f4cc06c937fc67650d118af04db8e83c0515cfa Mon Sep 17 00:00:00 2001 From: mirakyux Date: Thu, 26 Nov 2026 09:05:33 +0800 Subject: [PATCH 6/6] test(workspace): isolate failed container listing result mapping --- rust/crates/workspace/src/containers.rs | 38 +++++++++++++++---------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/rust/crates/workspace/src/containers.rs b/rust/crates/workspace/src/containers.rs index d8f1d493..686268a3 100644 --- a/rust/crates/workspace/src/containers.rs +++ b/rust/crates/workspace/src/containers.rs @@ -256,21 +256,6 @@ printf 'abc123\tweb,alias\tnginx:1\tUp 2 hours\n'"#, ); } - #[test] - fn failed_listings_are_available_with_the_message_and_no_containers() { - let fake = FakeEngine::new( - "stopped", - "printf 'Cannot connect to the Docker daemon. Is the docker daemon running?\\n' >&2\nexit 1", - ); - let listed = list_with(here(ContainerEngine::Docker), Some(&fake.program)).unwrap(); - assert!(listed.available); - assert!(listed.containers.is_empty()); - assert_eq!( - listed.diagnostics, - "Cannot connect to the Docker daemon. Is the docker daemon running?" - ); - } - #[test] fn a_missing_engine_is_unavailable() { let fake = FakeEngine::new("missing", "exit 0"); @@ -292,3 +277,26 @@ printf 'abc123\tweb,alias\tnginx:1\tUp 2 hours\n'"#, assert!(decode(serde_json::json!({})).is_err()); } } + +#[cfg(test)] +mod result_tests { + use super::*; + + #[test] + fn failed_listings_are_available_with_the_message_and_no_containers() { + // This contract concerns an engine that ran and exited nonzero. A + // freshly written executable adds an unrelated spawn failure boundary; + // CLI launch and arguments are covered by the Unix fixture above. + let listed = answer( + false, + b"", + b"Cannot connect to the Docker daemon. Is the docker daemon running?\n", + ); + assert!(listed.available); + assert!(listed.containers.is_empty()); + assert_eq!( + listed.diagnostics, + "Cannot connect to the Docker daemon. Is the docker daemon running?" + ); + } +}