diff --git a/rust/contracts/rust-core-api.md b/rust/contracts/rust-core-api.md index 372fa950..6e499b45 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`) | @@ -3660,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` / @@ -6805,6 +6814,19 @@ 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: [{ 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 `{ 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` (`1` invoked, `2` trigger character, `3` incomplete-list refresh) and `triggerCharacter` (required and one character for kind `2`). Missing context @@ -8583,26 +8605,89 @@ 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 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}`. 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. `editor.preferences.resolve` accepts optional `lineNumbers`, `whitespace`, `inlayHints`, -`cursorStyle` (`line`, `block`, `underline`), `cursorBlink` and `autoSaveDelayMilliseconds`. -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. +`indentGuides`, `rainbowIndentGuides`, +`cursorStyle` (`line`, `block`, `underline`), `cursorBlink`, `autoSaveDelayMilliseconds`, +`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 +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. +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, 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 +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`. +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 +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, 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. 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/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..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,8 +32,28 @@ 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) + } + 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/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/core/src/tests/editor_dispatch.rs b/rust/crates/core/src/tests/editor_dispatch.rs index d57aa7f0..d7b99d8f 100644 --- a/rust/crates/core/src/tests/editor_dispatch.rs +++ b/rust/crates/core/src/tests/editor_dispatch.rs @@ -1,9 +1,89 @@ //! 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 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!( + "../../../../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/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 27d8b89d..c63a2074 100644 --- a/rust/crates/editor/src/find.rs +++ b/rust/crates/editor/src/find.rs @@ -4,14 +4,18 @@ //! 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; 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)] @@ -21,6 +25,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 +55,47 @@ 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])) +} + +/// 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`). /// @@ -58,6 +106,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 +135,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) @@ -101,33 +152,66 @@ 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 mut record = |at: usize, + through: usize, + captures: Option<®ex::Captures<'_>>| + -> Result { if matches.len() == MAX_MATCHES { - truncated = true; - break; + return Ok(false); } - 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()})); + 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":start + m.end(), "text":inserted})); + 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() { @@ -156,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(); @@ -196,6 +319,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/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..b7b0da98 100644 --- a/rust/crates/editor/src/preferences.rs +++ b/rust/crates/editor/src/preferences.rs @@ -4,20 +4,83 @@ use lithe_protocol::{CoreError, ErrorCode}; use serde::Deserialize; use serde_json::{json, Value}; +const MAX_RAINBOW_COLORS: usize = 8; +const LIGHT_RAINBOW_COLORS: &[&str] = &[ + "#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68", +]; +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, + indent_guides: Option, + rainbow_indent_guides: Option, inlay_hints: Option, 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. + #[serde(default, deserialize_with = "retain_palette")] + rainbow_light_colors: Option, + #[serde(default, deserialize_with = "retain_palette")] + rainbow_dark_colors: Option, +} + +// 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()); + 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 { + 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 { + 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() { @@ -25,31 +88,85 @@ 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), "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), + "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(); 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); assert_eq!(value["autoSaveDelayMilliseconds"], 1500); + assert_eq!(value["rainbowBrackets"], false); + assert_eq!(value["rainbowVariables"], false); + 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() { + 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(); @@ -59,4 +176,30 @@ 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 [ + Value::Null, + 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, + "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["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 new file mode 100644 index 00000000..7516e8d5 --- /dev/null +++ b/rust/crates/editor/src/rainbow_brackets.rs @@ -0,0 +1,181 @@ +//! 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::{json, Value}; + +/// 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 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), + 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 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"))?; + 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 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. + 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 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); + (open.len(), Some(colors[opener].offset)) + } else { + continue; + }; + kinds.push(kind); + colors.push(Color { + offset: token.offset, + depth: depth as u32, + match_offset, + }); + } + Ok(json!({ "colors": colors })) +} + +#[cfg(test)] +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) + .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..d9efd55e --- /dev/null +++ b/rust/crates/editor/src/rainbow_variables.rs @@ -0,0 +1,139 @@ +//! 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); + } + // 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) + .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"], 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(); + 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..1637ced5 100644 --- a/rust/crates/lsp-client/src/client/results.rs +++ b/rust/crates/lsp-client/src/client/results.rs @@ -39,6 +39,7 @@ pub(crate) fn lsp_feature_result_for_method( Some("textDocument/documentSymbol") => Some(json!({ "symbols": parse_document_symbols(result) })), + Some("textDocument/documentHighlight") => Some(parse_document_highlights(result)), Some("textDocument/inlayHint") => Some(json!({ "hints": parse_inlay_hints(result) })), @@ -713,6 +714,35 @@ 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) -> Value { + const MAX_HIGHLIGHTS: usize = 4096; + let mut highlights = 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); + 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 { result .as_array() @@ -1028,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-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..089efd90 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": [], "truncated": false})), + ] + .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/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?" + ); + } +} diff --git a/rust/fixtures/editor/ide-essentials-v1.json b/rust/fixtures/editor/ide-essentials-v1.json index fd5e1ad1..6839339a 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", @@ -58,12 +102,44 @@ "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, + "rainbowLightColors": ["#A4262C", "#0657A4", "#6D3298", "#00695C", "#8A5200", "#394B68"], + "rainbowDarkColors": ["#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, "autoSaveDelayMilliseconds": 1500, "minimumAutoSaveDelayMilliseconds": 250, - "maximumAutoSaveDelayMilliseconds": 60000 + "maximumAutoSaveDelayMilliseconds": 60000, + "rainbowBrackets": false, + "rainbowVariables": false, + "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 new file mode 100644 index 00000000..b588ba3d --- /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, "matchOffset": 4 }, + { "offset": 3, "depth": 1 }, + { "offset": 4, "depth": 0, "matchOffset": 2 }, + { "offset": 6, "depth": 0 } + ] + } + }, + { + "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..eab282a6 --- /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": 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 } + ] + } + }, + { + "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..2a0db0b9 --- /dev/null +++ b/rust/fixtures/lsp/document-highlight-v1.json @@ -0,0 +1,21 @@ +{ + "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}, "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" } ] }