diff --git a/crates/ide-host/src/plugins/commands.rs b/crates/ide-host/src/plugins/commands.rs index 0f33ee38a9..9be5e95fc6 100644 --- a/crates/ide-host/src/plugins/commands.rs +++ b/crates/ide-host/src/plugins/commands.rs @@ -7,8 +7,8 @@ use super::{ use crate::Host; use crate::ops::blocking; use ide_command::command; -use ide_core::{IdeResult, RequestId}; -use ide_plugin::Invocation; +use ide_core::{DocId, IdeError, IdeResult, Range, RequestId}; +use ide_plugin::{Invocation, ProviderDocument, SyntaxDecorationBatch, SyntaxNodeSnapshot}; use ide_workspace::settings::SettingsScope; use std::collections::BTreeMap; use std::path::PathBuf; @@ -236,6 +236,72 @@ pub fn plugin_decoration_sets(plugins: &Arc) -> BTreeMap) -> Vec { + plugins.syntax_decoration_languages() +} + +/// Foreground marks for one open document. An unknown document, a document the +/// window does not have, or an invalid snapshot answers with no marks. +#[allow(clippy::too_many_arguments)] +#[command(trust = trusted)] +pub async fn plugin_syntax_decorations( + host: &Host, + plugins: &Arc, + window: &str, + request: RequestId, + doc: DocId, + ranges: Vec, + nodes: Vec, + epoch: u64, +) -> IdeResult { + let Ok(project) = host.project(window) else { + return Ok(SyntaxDecorationBatch { version: 0, epoch, stale: false, marks: Vec::new() }); + }; + let plugins = plugins.clone(); + let documents = project.documents.clone(); + let cancel = host.begin_project_request(window, request); + let work_cancel = cancel.clone(); + let result = blocking(move || { + if work_cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Ok(snap) = documents.snapshot(doc) else { return Ok(None) }; + let version = u64::from(snap.version); + // `large` is the code insight limit stamped when the document was opened. + if snap.large { + return Ok(Some((version, Vec::new()))); + } + let document = ProviderDocument { path: snap.path.0, language: snap.language.0, version, text: snap.text }; + let marks = plugins.provide_syntax_decorations(&document, &ranges, &nodes, &work_cancel); + Ok(Some((version, marks))) + }) + .await; + host.end_request(request); + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + let Some((version, marks)) = result? else { + return Ok(SyntaxDecorationBatch { version: 0, epoch, stale: false, marks: Vec::new() }); + }; + let current = host + .project(window) + .ok() + .filter(|current| Arc::ptr_eq(current, &project)) + .and_then(|project| project.documents.version(doc).ok()) + .map(u64::from); + if current != Some(version) { + return Ok(SyntaxDecorationBatch { + version: current.unwrap_or(version), + epoch, + stale: true, + marks: Vec::new(), + }); + } + Ok(SyntaxDecorationBatch { version, epoch, stale: false, marks }) +} + /// Every plugin's console highlight rules (later changes arrive as `consoleRulesChanged`). #[command(trust = trusted)] pub fn plugin_console_rules(plugins: &Arc) -> BTreeMap> { @@ -373,6 +439,8 @@ ide_command::domain!( plugin_set_active_file, plugin_set_ui_locale, plugin_status_items, + plugin_syntax_decoration_languages, + plugin_syntax_decorations, plugin_terminal_session_close, plugin_terminal_session_spawn, ); diff --git a/crates/ide-host/src/plugins/providers.rs b/crates/ide-host/src/plugins/providers.rs index bbd51bbe7c..e9a4a49a4f 100644 --- a/crates/ide-host/src/plugins/providers.rs +++ b/crates/ide-host/src/plugins/providers.rs @@ -19,7 +19,9 @@ //! description = "Create one at https://example.com/keys" //! ``` -use ide_extension::{Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id}; +use ide_extension::{ + Capability, Disposable, ExtensionPoint, Package, Placement, Prepared, UiDecl, decode, validate_item_id, +}; use parking_lot::RwLock; use serde::{Deserialize, Serialize}; use std::collections::{HashMap, HashSet}; @@ -56,6 +58,7 @@ pub enum ProviderKind { GutterActions, HoverActions, Injections, + SyntaxDecorations, } #[derive(Clone, Debug, Deserialize)] @@ -105,6 +108,22 @@ impl Providers { self.matching::>(kind, language).into_iter().map(|(plugin, _)| plugin).collect() } + /// Languages declared for `kind`, including `"*"` when a plugin asks for every language. + pub fn languages(&self, kind: ProviderKind) -> Vec { + let mut out = Vec::new(); + for (_, _, kinds, languages) in self.items.read().iter() { + if !kinds.contains(&kind) { + continue; + } + for language in languages { + if !out.contains(language) { + out.push(language.clone()); + } + } + } + out + } + /// One coherent declaration snapshot, preserving the first match per plugin. fn matching>(&self, kind: ProviderKind, language: &str) -> T { let items = self.items.read(); @@ -190,6 +209,12 @@ impl ExtensionPoint for ProvidersPoint { if d.kinds.contains(&ProviderKind::InlayHints) { pkg.manifest.needs_api("contributes.providers: inlay-hints", 3)?; } + if d.kinds.contains(&ProviderKind::SyntaxDecorations) { + pkg.manifest.needs_api("contributes.providers: syntax-decorations", 20)?; + if !pkg.manifest.capabilities.all().any(|cap| *cap == Capability::EditorRead) { + return Err("contributes.providers: syntax-decorations needs the `editor.read` capability".into()); + } + } if d.kinds.iter().any(|k| { matches!( k, @@ -390,6 +415,40 @@ impl PluginHost { .collect() } + fn edit_calls_cancellable( + &self, + plugins: impl IntoIterator>, + cancel: &CancellationToken, + f: impl FnOnce(&mut Runtime, Duration) -> Result + Clone + Send + 'static, + ) -> Vec<(Arc, R)> { + std::thread::scope(|scope| { + let calls: Vec<_> = plugins + .into_iter() + .map(|plugin| { + let f = f.clone(); + scope.spawn(move || { + if cancel.is_cancelled() { + return None; + } + let (actor, activated) = self.ensure_active(&plugin, None).ok()?; + if activated { + self.changed(); + } + let started = Instant::now(); + let hard = self.limits.edit_hard; + let result = + actor.call_edit_cancellable(cancel, CANCEL_GRACE, self.limits.edit_soft, move |rt| { + f(rt, hard) + }); + let items = self.finish_provider_call(&plugin, &actor, started, result)?; + (!cancel.is_cancelled()).then_some((plugin, items)) + }) + }) + .collect(); + calls.into_iter().filter_map(|call| call.join().ok().flatten()).collect() + }) + } + pub(super) fn finish_provider_call( &self, plugin: &Arc, @@ -601,33 +660,19 @@ impl PluginHost { doc: &ProviderDocument, cancel: &CancellationToken, ) -> Vec<(String, Vec)> { - std::thread::scope(|scope| { - let calls: Vec<_> = self - .provider_plugins(ProviderKind::Diagnostics, &doc.language) - .into_iter() - .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) - .map(|p| { - scope.spawn(move || { - if cancel.is_cancelled() { - return None; - } - let (actor, activated) = self.ensure_active(&p, None).ok()?; - if activated { - self.changed(); - } - let (d, timeout) = (doc.clone(), self.limits.edit_hard); - let started = Instant::now(); - let result = - actor.call_edit_cancellable(cancel, CANCEL_GRACE, self.limits.edit_soft, move |rt| { - rt.provide_diagnostics(&d, timeout) - }); - let items = self.finish_provider_call(&p, &actor, started, result)?; - (!cancel.is_cancelled()).then(|| (p.id().to_owned(), items)) - }) - }) - .collect(); - calls.into_iter().filter_map(|call| call.join().ok().flatten()).collect() - }) + let mut plugins = self + .provider_plugins(ProviderKind::Diagnostics, &doc.language) + .into_iter() + .filter(|p| p.dev_root.is_none() || p.dev_root.as_deref() == project) + .peekable(); + if plugins.peek().is_none() { + return Vec::new(); + } + let doc = Arc::new(doc.clone()); + self.edit_calls_cancellable(plugins, cancel, move |rt, timeout| rt.provide_diagnostics(&doc, timeout)) + .into_iter() + .map(|(plugin, items)| (plugin.id().to_owned(), items)) + .collect() } pub fn provide_hover(&self, doc: &ProviderDocument, at: ide_core::Pos) -> Vec { @@ -653,6 +698,62 @@ impl PluginHost { .collect() } + /// Theme-token marks for one open document. Plugins that do not declare the + /// language are not called. An invalid snapshot calls none of them. + pub fn provide_syntax_decorations( + &self, + doc: &ProviderDocument, + ranges: &[ide_core::Range], + nodes: &[ide_plugin::SyntaxNodeSnapshot], + cancel: &CancellationToken, + ) -> Vec { + if ranges.is_empty() || nodes.is_empty() || cancel.is_cancelled() { + return Vec::new(); + } + let plugins: Vec<_> = self + .syntax_decoration_plugins(&doc.language) + .filter(|p| p.dev_root.as_ref().is_none_or(|root| doc.path.starts_with(root))) + .collect(); + if plugins.is_empty() || ide_plugin::validate_syntax_snapshot(&doc.text, ranges, nodes).is_err() { + return Vec::new(); + } + let owned_ranges = Arc::<[_]>::from(ranges); + let owned_nodes = Arc::<[_]>::from(nodes); + let d = Arc::new(doc.clone()); + self.edit_calls_cancellable(plugins, cancel, move |rt, timeout| { + rt.provide_syntax_decorations(&d, &owned_ranges, &owned_nodes, timeout) + }) + .into_iter() + .flat_map(|(plugin, marks)| { + let id = plugin.id().to_owned(); + ide_plugin::filter_syntax_marks(&doc.text, ranges, marks).into_iter().map(move |mark| { + ide_plugin::SyntaxDecoration { + plugin: id.clone(), + range: mark.range, + token: mark.token, + foreground: mark.foreground, + } + }) + }) + .take(ide_plugin::MAX_SYNTAX_MARKS) + .collect() + } + + fn syntax_decoration_plugins(&self, language: &str) -> impl Iterator> { + self.provider_plugins(ProviderKind::SyntaxDecorations, language) + .into_iter() + .filter(|plugin| plugin.meta.lock().granted.contains(&Capability::EditorRead)) + } + + /// Languages with a `syntax-decorations` provider, without loading any plugin. + pub fn syntax_decoration_languages(&self) -> Vec { + self.providers + .languages(ProviderKind::SyntaxDecorations) + .into_iter() + .filter(|language| self.syntax_decoration_plugins(language).next().is_some()) + .collect() + } + /// Whether a usable plugin offers ghost text for `language`. pub fn offers_inline_completion(&self, language: &str) -> bool { !self.provider_plugins(ProviderKind::InlineCompletion, language).is_empty() diff --git a/crates/ide-host/tests/plugin_syntax_decorations.rs b/crates/ide-host/tests/plugin_syntax_decorations.rs new file mode 100644 index 0000000000..7a79417134 --- /dev/null +++ b/crates/ide-host/tests/plugin_syntax_decorations.rs @@ -0,0 +1,357 @@ +mod common; + +use ide_core::{CancellationToken, Pos, Range, RequestId}; +use ide_host::plugins::{Consent, PluginHost}; +use ide_host::{Host, plugins::commands::plugin_syntax_decorations}; +use ide_plugin::{Limits, ProviderDocument, SyntaxNodeSnapshot}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +fn fixture_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/syntax-decorations") +} + +fn host(dir: &Path) -> PluginHost { + let limits = ide_plugin::Limits { + edit_soft: Duration::from_secs(5), + edit_hard: Duration::from_secs(10), + ..ide_plugin::Limits::default() + }; + PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap() +} + +fn doc(dir: &Path, language: &str, version: u64) -> ProviderDocument { + ProviderDocument { path: dir.join("a.js"), language: language.into(), version, text: "const value = 1;\n".into() } +} + +fn node(name: &str, parent: Option) -> SyntaxNodeSnapshot { + SyntaxNodeSnapshot { name: name.into(), range: Range::new(Pos::new(0, 6), Pos::new(0, 11)), parent } +} + +fn pair() -> Vec { + vec![node("Script", None), node("VariableName", Some(0))] +} + +fn asked() -> Range { + Range::new(Pos::new(0, 0), Pos::new(0, 16)) +} + +#[test] +fn a_parented_node_is_marked_with_the_theme_token() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + let marks = host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 4), + &[asked()], + &pair(), + &CancellationToken::new(), + ); + assert_eq!(marks.len(), 1); + assert_eq!(marks[0].plugin, "test.syntax-decorations"); + assert_eq!(marks[0].token, "rainbow-1"); + assert_eq!(marks[0].range, Range::new(Pos::new(0, 6), Pos::new(0, 11))); +} + +#[test] +fn colour_marks_are_normalised_and_invalid_ones_dropped() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + let marks = host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 7), + &[asked()], + &pair(), + &CancellationToken::new(), + ); + assert_eq!(marks.len(), 1, "{marks:?}"); + assert_eq!( + marks[0].foreground, + Some(ide_plugin::SyntaxForeground { dark: "#80cbc4".into(), light: "#23766f".into() }) + ); +} + +#[test] +fn a_zero_version_and_another_language_produce_nothing() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + assert!( + host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 0), + &[asked()], + &pair(), + &CancellationToken::new() + ) + .is_empty() + ); + assert!( + host.provide_syntax_decorations(&doc(tmp.path(), "yaml", 4), &[asked()], &pair(), &CancellationToken::new()) + .is_empty() + ); +} + +#[test] +fn an_invalid_snapshot_does_not_call_the_plugin() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + let marks = host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 4), + &[asked()], + &[node("A", Some(9))], + &CancellationToken::new(), + ); + assert!(marks.is_empty()); +} + +#[test] +fn declining_editor_read_disables_the_provider() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + let pkg = tmp.path().join("optional"); + std::fs::create_dir_all(pkg.join("dist")).unwrap(); + std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap(); + let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap(); + std::fs::write(pkg.join("plugin.toml"), manifest.replace("required =", "optional =")).unwrap(); + host.install_from_dir(&pkg, &Consent::default()).unwrap(); + assert!(host.syntax_decoration_languages().is_empty()); + assert!( + host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 4), + &[asked()], + &pair(), + &CancellationToken::new(), + ) + .is_empty() + ); +} + +#[test] +fn uninstalling_the_plugin_drops_its_marks() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + assert_eq!( + host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 4), + &[asked()], + &pair(), + &CancellationToken::new() + ) + .len(), + 1 + ); + host.uninstall("test.syntax-decorations").unwrap(); + assert!( + host.provide_syntax_decorations( + &doc(tmp.path(), "javascript", 4), + &[asked()], + &pair(), + &CancellationToken::new() + ) + .is_empty() + ); +} + +#[test] +fn the_kind_needs_plugin_api_1_20() { + let tmp = tempfile::tempdir().unwrap(); + let host = host(tmp.path()); + let pkg = tmp.path().join("old"); + std::fs::create_dir_all(pkg.join("dist")).unwrap(); + std::fs::copy(fixture_dir().join("dist/plugin.wasm"), pkg.join("dist/plugin.wasm")).unwrap(); + let manifest = std::fs::read_to_string(fixture_dir().join("plugin.toml")).unwrap(); + std::fs::write(pkg.join("plugin.toml"), manifest.replace("\"^1.20\"", "\"^1.0\"")).unwrap(); + let err = host.install_from_dir(&pkg, &Consent::all()).unwrap_err(); + assert!(err.message.contains("new in plugin API 1.20"), "{}", err.message); +} + +fn misbehave_wasm() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm") +} + +/// The shared misbehave component, declared here as a syntax-decoration provider. +/// Its own manifest stays on `^1.0` and does not advertise this kind. +fn misbehave_provider(dir: &Path) -> PathBuf { + let pkg = dir.join("misbehave-syntax"); + std::fs::create_dir_all(pkg.join("dist")).unwrap(); + std::fs::copy(misbehave_wasm(), pkg.join("dist/plugin.wasm")).unwrap(); + std::fs::write( + pkg.join("plugin.toml"), + "\ +id = \"misbehave\" +name = \"Misbehave\" +version = \"0.0.2\" +engines.openidea = \"^1.20\" +wasm = \"dist/plugin.wasm\" + +[capabilities] +required = [\"editor.read\"] + +[[contributes.providers]] +kinds = [\"syntax-decorations\"] +languages = [\"javascript\"] +", + ) + .unwrap(); + pkg +} + +fn tight(dir: &Path) -> PluginHost { + let limits = Limits { + edit_soft: Duration::from_millis(50), + edit_hard: Duration::from_millis(400), + fuel: u64::MAX, + restart_backoff: Duration::ZERO, + ..Limits::default() + }; + PluginHost::new(dir.join("plugins"), Arc::new(|_: Option<&str>, _| {}), limits).unwrap() +} + +/// The first name is how misbehave fails. The second node is what the fixture marks. +fn signal(name: &str) -> Vec { + vec![ + SyntaxNodeSnapshot { name: name.into(), range: Range::new(Pos::new(0, 0), Pos::new(0, 5)), parent: None }, + node("VariableName", Some(0)), + ] +} + +fn install_pair(host: &PluginHost, dir: &Path) { + host.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + host.install_from_dir(&misbehave_provider(dir), &Consent::all()).unwrap(); +} + +fn ready(host: &PluginHost, dir: &Path) { + let document = doc(dir, "javascript", 4); + let mut ok = false; + for _ in 0..30 { + let marks = host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()); + let fixture = marks.iter().any(|m| m.plugin == "test.syntax-decorations"); + let mis = host.info_of("misbehave").is_ok_and(|info| info.stats.activations >= 1); + if fixture && mis { + ok = true; + break; + } + std::thread::sleep(Duration::from_millis(40)); + } + assert!(ok, "plugins did not finish activating"); +} + +fn keeps_the_other(marks: &[ide_plugin::SyntaxDecoration]) { + assert!(marks.iter().any(|m| m.plugin == "test.syntax-decorations" && m.token == "rainbow-1"), "{marks:?}"); + assert!(marks.iter().all(|m| m.plugin != "misbehave"), "{marks:?}"); +} + +#[test] +fn a_trapped_plugin_drops_its_marks_and_leaves_the_other() { + let tmp = tempfile::tempdir().unwrap(); + let host = tight(tmp.path()); + install_pair(&host, tmp.path()); + ready(&host, tmp.path()); + let document = doc(tmp.path(), "javascript", 4); + keeps_the_other(&host.provide_syntax_decorations( + &document, + &[asked()], + &signal("panic"), + &CancellationToken::new(), + )); + assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1); +} + +#[test] +fn a_slow_plugin_is_dropped_and_the_other_answers() { + let tmp = tempfile::tempdir().unwrap(); + let host = tight(tmp.path()); + install_pair(&host, tmp.path()); + ready(&host, tmp.path()); + let document = doc(tmp.path(), "javascript", 4); + keeps_the_other(&host.provide_syntax_decorations( + &document, + &[asked()], + &signal("sleep:150"), + &CancellationToken::new(), + )); + let info = host.info_of("misbehave").unwrap(); + assert!(info.stats.slow_calls >= 1, "{:?}", info.stats); + assert_eq!(info.stats.crashes, 0, "{:?}", info.stats); + assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1); +} + +#[test] +fn uninstalling_a_spinning_plugin_keeps_the_other_answering() { + let tmp = tempfile::tempdir().unwrap(); + let host = Arc::new(tight(tmp.path())); + install_pair(&host, tmp.path()); + ready(&host, tmp.path()); + let document = doc(tmp.path(), "javascript", 4); + let running = { + let host = host.clone(); + let document = document.clone(); + std::thread::spawn(move || { + host.provide_syntax_decorations(&document, &[asked()], &signal("spin"), &CancellationToken::new()) + }) + }; + std::thread::sleep(Duration::from_millis(20)); + host.uninstall("misbehave").unwrap(); + keeps_the_other(&running.join().unwrap()); + assert_eq!(host.provide_syntax_decorations(&document, &[asked()], &pair(), &CancellationToken::new()).len(), 1); +} + +fn bump(project: &ide_host::Project, doc: ide_core::DocId) -> u32 { + project + .documents + .apply_edits( + doc, + &[ide_core::TextEdit { range: Range::new(Pos::new(0, 16), Pos::new(0, 16)), new_text: " ".into() }], + ) + .unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_code_insight_limit_gates_the_provider_without_a_fixed_character_ceiling() { + let tmp = tempfile::tempdir().unwrap(); + let root = dunce::canonicalize(tmp.path()).unwrap(); + let file = root.join("a.js"); + std::fs::write(&file, "const value = 1;\n").unwrap(); + let plugins = + Arc::new(PluginHost::new(root.join("plugins"), Arc::new(|_: Option<&str>, _| {}), Limits::default()).unwrap()); + plugins.install_from_dir(&fixture_dir(), &Consent::all()).unwrap(); + + let open_host = Host::new(common::host_config(&root.join("open"))); + open_host.set_project_trust(&root, true, false).await.unwrap(); + let open = open_host.open_project("main", &root).unwrap(); + let small = open.documents.open(&file).unwrap(); + assert!(!small.large); + assert!(bump(&open, small.id) >= 1); + let allowed = + plugin_syntax_decorations(&open_host, &plugins, "main", RequestId(1), small.id, vec![asked()], pair(), 2) + .await + .unwrap(); + assert_eq!(allowed.marks.len(), 1, "{allowed:?}"); + assert_eq!(allowed.marks[0].token, "rainbow-1"); + + let cancelled = RequestId(2); + open_host.cancel_request(cancelled); + let error = plugin_syntax_decorations(&open_host, &plugins, "main", cancelled, small.id, vec![asked()], pair(), 3) + .await + .unwrap_err(); + assert_eq!(error.kind, ide_core::error::ErrorKind::Cancelled); + + let limited_host = Host::new(common::host_config(&root.join("limited"))); + limited_host.set_project_trust(&root, true, false).await.unwrap(); + let limited = limited_host.open_project("main", &root).unwrap(); + let defaults = ide_workspace::FileDefaults { max_code_insight_bytes: 1, ..Default::default() }; + limited.documents.set_file_defaults(defaults); + let large = limited.documents.open(&file).unwrap(); + assert!(large.large, "a one-byte insight limit marks the file without allocating a huge buffer"); + assert!(bump(&limited, large.id) >= 1, "the gate is only visible once the fixture would have answered"); + let blocked = + plugin_syntax_decorations(&limited_host, &plugins, "main", RequestId(1), large.id, vec![asked()], pair(), 1) + .await + .unwrap(); + assert!(blocked.marks.is_empty(), "{blocked:?}"); + assert!(!blocked.stale); + assert!(blocked.version >= 1, "{blocked:?}"); +} diff --git a/crates/ide-plugin/src/lib.rs b/crates/ide-plugin/src/lib.rs index 679d7e0f61..4767eee8af 100644 --- a/crates/ide-plugin/src/lib.rs +++ b/crates/ide-plugin/src/lib.rs @@ -31,6 +31,12 @@ pub use wasmtime::component::Component; mod execution; pub use execution::*; +mod syntax_decorations; +pub use syntax_decorations::{ + MAX_SYNTAX_MARKS, MAX_SYNTAX_NAME, MAX_SYNTAX_NODES, MAX_SYNTAX_RANGES, SYNTAX_TOKENS, SyntaxSnapshotError, + filter_syntax_marks, syntax_foreground, syntax_token_allowed, validate_syntax_snapshot, +}; + pub use ide_core::remote_settings::PluginRunTarget; pub mod language_features; diff --git a/crates/ide-plugin/src/runtime.rs b/crates/ide-plugin/src/runtime.rs index 245d59949e..37d719b955 100644 --- a/crates/ide-plugin/src/runtime.rs +++ b/crates/ide-plugin/src/runtime.rs @@ -26,7 +26,8 @@ use crate::wit_host::run_target_validation_bindings::exports::openidea::plugin:: use crate::wit_host::search_bindings::exports::openidea::plugin::search_provider as wit_search; use crate::wit_host::{ bindings, commit_checks_bindings, details_bindings, endpoints_bindings, file_actions_bindings, hover_bindings, - indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings, views_bindings, + indexing_bindings, inlay_bindings, providers_bindings, semantic_bindings, syntax_bindings, + syntax_decoration_bindings, views_bindings, }; use ide_core::CancellationToken; use ide_core::ipc_path::to_ipc; @@ -60,6 +61,7 @@ use inlay_bindings::exports::openidea::plugin::inlay_hints_provider as wit_inlay use providers_bindings::exports::openidea::plugin::providers as wit_prov; use semantic_bindings::exports::openidea::plugin::semantic_tokens_provider as wit_sem; use syntax_bindings::exports::openidea::plugin::syntax_provider as wit_syntax; +use syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider as wit_syn; use views_bindings::exports::openidea::plugin::view_provider as wit_view; use views_bindings::openidea::plugin::view_types as wit_vt; @@ -973,6 +975,7 @@ struct Exports { hover: Option, commit_checks: Option, inlay: Option, + syntax_decorations: Option, endpoints: Option, search: Option, hover_actions: Option, @@ -1135,6 +1138,7 @@ impl Runtime { let hover_indices = wit_hover::GuestIndices::new(&pre).ok(); let commit_check_indices = wit_cc::GuestIndices::new(&pre).ok(); let inlay_indices = wit_inlay::GuestIndices::new(&pre).ok(); + let syntax_decoration_indices = wit_syn::GuestIndices::new(&pre).ok(); let endpoint_indices = wit_endpoints::GuestIndices::new(&pre).ok(); let search_indices = wit_search::GuestIndices::new(&pre).ok(); let hover_actions_indices = wit_hia::GuestIndices::new(&pre).ok(); @@ -1211,6 +1215,10 @@ impl Runtime { Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), None => None, }; + let syntax_decorations = match syntax_decoration_indices { + Some(indices) => Some(indices.load(&mut store, &instance).map_err(api_hint)?), + None => None, + }; let search = search_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; let hover_actions = hover_actions_indices.map(|i| i.load(&mut store, &instance)).transpose().map_err(api_hint)?; @@ -1239,6 +1247,7 @@ impl Runtime { hover, commit_checks, inlay, + syntax_decorations, endpoints, search, hover_actions, @@ -1882,6 +1891,45 @@ impl Runtime { .collect()) } + pub fn provide_syntax_decorations( + &mut self, + doc: &ProviderDocument, + ranges: &[ide_core::Range], + nodes: &[crate::SyntaxNodeSnapshot], + timeout: Duration, + ) -> Result, CallError> { + if self.exports.syntax_decorations.is_none() { + return Err(CallError::missing_export("syntax-decorations-provider")); + } + let request = wit_syn::DecorationRequest { + document: wit_syn::Document { + path: to_ipc(&doc.path), + language: doc.language.clone(), + version: doc.version, + }, + ranges: ranges.iter().copied().map(range_to_wit).collect(), + nodes: nodes + .iter() + .map(|n| wit_syn::SyntaxNode { name: n.name.clone(), range: range_to_wit(n.range), parent: n.parent }) + .collect(), + }; + let marks = self.call(Invocation::default(), timeout, |e, store| { + e.syntax_decorations.as_ref().expect("checked").call_syntax_decorations(store, &request) + })?; + Ok(marks + .into_iter() + .filter_map(|m| { + let foreground = match &m.foreground { + Some(f) => Some(crate::syntax_foreground(&f.dark, &f.light)?), + None if crate::syntax_token_allowed(&m.token) => None, + None => return None, + }; + Some(crate::PluginSyntaxMark { range: range_from_wit(m.range), token: m.token, foreground }) + }) + .take(MAX_PROVIDER_ITEMS) + .collect()) + } + pub fn activate(&mut self) -> Result<(), CallError> { let data = self.store.data(); let ctx = wit_types::Context { diff --git a/crates/ide-plugin/src/syntax_decorations.rs b/crates/ide-plugin/src/syntax_decorations.rs new file mode 100644 index 0000000000..4904e92ce2 --- /dev/null +++ b/crates/ide-plugin/src/syntax_decorations.rs @@ -0,0 +1,228 @@ +//! Bounds for the syntax-decoration provider. The editor builds the snapshot +//! from the syntax tree it already has; this module only checks that the +//! snapshot and the marks stay inside the document. + +use crate::{PluginSyntaxMark, SyntaxForeground, SyntaxNodeSnapshot}; +use ide_core::{Pos, Range}; + +/// Nodes included in one request, including ancestors of the requested ranges. +pub const MAX_SYNTAX_NODES: usize = 8_192; +/// Visible ranges plus sticky header lines. +pub const MAX_SYNTAX_RANGES: usize = 32; +pub const MAX_SYNTAX_NAME: usize = 128; +/// Same cap as the other editor providers. +pub const MAX_SYNTAX_MARKS: usize = 10_000; + +/// Theme tokens the host maps onto `--syn-rainbow-1` … `--syn-rainbow-5`. +pub const SYNTAX_TOKENS: [&str; 5] = ["rainbow-1", "rainbow-2", "rainbow-3", "rainbow-4", "rainbow-5"]; + +/// A mark colour as the editor renders it: `#rrggbb` or `#rrggbbaa`, lower case. +fn mark_color(color: &str) -> Option { + let hex = color.strip_prefix('#')?; + ((hex.len() == 6 || hex.len() == 8) && hex.bytes().all(|b| b.is_ascii_hexdigit())) + .then(|| format!("#{}", hex.to_ascii_lowercase())) +} + +/// The foreground a plugin gave, normalised; `None` when either colour is invalid. +pub fn syntax_foreground(dark: &str, light: &str) -> Option { + Some(SyntaxForeground { dark: mark_color(dark)?, light: mark_color(light)? }) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SyntaxSnapshotError { + TooManyRanges, + TooManyNodes, + BadName, + BadParent, + BadRange, +} + +struct Lines { + lens: Vec, +} + +impl Lines { + fn new(text: &str) -> Self { + let mut lens = Vec::new(); + for line in text.split('\n') { + let line = line.strip_suffix('\r').unwrap_or(line); + lens.push(u32::try_from(line.encode_utf16().count()).unwrap_or(u32::MAX)); + } + if lens.is_empty() { + lens.push(0); + } + Self { lens } + } + + fn contains(&self, range: Range) -> bool { + let ok = |p: Pos| (p.line as usize) < self.lens.len() && p.col <= self.lens[p.line as usize]; + ok(range.start) && ok(range.end) && range.start <= range.end + } +} + +fn overlaps(a: Range, b: Range) -> bool { + a.start < b.end && b.start < a.end +} + +fn parents_ok(nodes: &[SyntaxNodeSnapshot]) -> bool { + let mut visiting = vec![false; nodes.len()]; + let mut checked = vec![false; nodes.len()]; + let mut path = Vec::new(); + for i in 0..nodes.len() { + let mut next = Some(i); + while let Some(index) = next { + if index >= nodes.len() || visiting[index] { + return false; + } + if checked[index] { + break; + } + visiting[index] = true; + path.push(index); + next = nodes[index].parent.map(|parent| parent as usize); + } + for index in path.drain(..) { + visiting[index] = false; + checked[index] = true; + } + } + true +} + +/// Reject a snapshot the editor should not have sent. An empty range list is +/// valid and means there is nothing to ask. +pub fn validate_syntax_snapshot( + text: &str, + ranges: &[Range], + nodes: &[SyntaxNodeSnapshot], +) -> Result<(), SyntaxSnapshotError> { + if ranges.len() > MAX_SYNTAX_RANGES { + return Err(SyntaxSnapshotError::TooManyRanges); + } + if nodes.len() > MAX_SYNTAX_NODES { + return Err(SyntaxSnapshotError::TooManyNodes); + } + let lines = Lines::new(text); + if ranges.iter().any(|r| !lines.contains(*r)) || nodes.iter().any(|n| !lines.contains(n.range)) { + return Err(SyntaxSnapshotError::BadRange); + } + if nodes.iter().any(|n| n.name.is_empty() || n.name.len() > MAX_SYNTAX_NAME) { + return Err(SyntaxSnapshotError::BadName); + } + if !parents_ok(nodes) { + return Err(SyntaxSnapshotError::BadParent); + } + Ok(()) +} + +pub fn syntax_token_allowed(token: &str) -> bool { + SYNTAX_TOKENS.contains(&token) +} + +/// Keep marks the plugin may paint: checked colours or an allowlisted token, a range inside the +/// document, and an overlap with a range the host asked about. +pub fn filter_syntax_marks(text: &str, ranges: &[Range], marks: Vec) -> Vec { + let lines = Lines::new(text); + marks + .into_iter() + .filter(|m| { + (m.foreground.is_some() || syntax_token_allowed(&m.token)) + && m.range.start < m.range.end + && lines.contains(m.range) + && ranges.iter().any(|r| overlaps(m.range, *r)) + }) + .take(MAX_SYNTAX_MARKS) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn range(line: u32, col: u32, end_col: u32) -> Range { + Range::new(Pos::new(line, col), Pos::new(line, end_col)) + } + + fn node(name: &str, parent: Option) -> SyntaxNodeSnapshot { + SyntaxNodeSnapshot { name: name.into(), range: range(0, 0, 1), parent } + } + + #[test] + fn a_parent_outside_the_range_is_accepted() { + let nodes = vec![node("Document", None), node("Key", Some(0))]; + assert_eq!(validate_syntax_snapshot("ab\n", &[range(0, 0, 1)], &nodes), Ok(())); + } + + #[test] + fn utf16_columns_follow_the_line() { + let text = "a😀b\n"; + let ok = range(0, 0, 4); + let past = range(0, 0, 5); + assert!(validate_syntax_snapshot(text, &[ok], &[]).is_ok()); + assert_eq!(validate_syntax_snapshot(text, &[past], &[]), Err(SyntaxSnapshotError::BadRange)); + } + + #[test] + fn an_empty_document_has_one_empty_line() { + assert!(validate_syntax_snapshot("", &[range(0, 0, 0)], &[]).is_ok()); + assert_eq!(validate_syntax_snapshot("", &[range(1, 0, 0)], &[]), Err(SyntaxSnapshotError::BadRange)); + } + + #[test] + fn a_bad_parent_rejects_the_snapshot() { + let nodes = vec![node("A", Some(1)), node("B", Some(0))]; + assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &nodes), Err(SyntaxSnapshotError::BadParent)); + let itself = vec![node("A", Some(0))]; + assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &itself), Err(SyntaxSnapshotError::BadParent)); + let missing = vec![node("A", Some(3))]; + assert_eq!(validate_syntax_snapshot("ab", &[range(0, 0, 1)], &missing), Err(SyntaxSnapshotError::BadParent)); + } + + #[test] + fn the_node_cap_is_enforced() { + let nodes = vec![node("A", None); MAX_SYNTAX_NODES + 1]; + assert_eq!(validate_syntax_snapshot("a", &[range(0, 0, 1)], &nodes), Err(SyntaxSnapshotError::TooManyNodes)); + } + + #[test] + fn marks_outside_the_request_or_the_token_list_are_dropped() { + let asked = range(0, 0, 2); + let marks = vec![ + PluginSyntaxMark { range: asked, token: "rainbow-2".into(), foreground: None }, + PluginSyntaxMark { range: asked, token: "red".into(), foreground: None }, + PluginSyntaxMark { range: range(0, 4, 5), token: "rainbow-1".into(), foreground: None }, + PluginSyntaxMark { + range: Range::new(Pos::new(0, 8), Pos::new(0, 1)), + token: "rainbow-1".into(), + foreground: None, + }, + PluginSyntaxMark { + range: Range::new(Pos::new(9, 0), Pos::new(9, 1)), + token: "rainbow-1".into(), + foreground: None, + }, + ]; + let kept = filter_syntax_marks("hello", &[asked], marks); + assert_eq!(kept, vec![PluginSyntaxMark { range: asked, token: "rainbow-2".into(), foreground: None }]); + } + + #[test] + fn foreground_colours_are_normalised_and_css_is_rejected() { + assert_eq!( + syntax_foreground("#80CBC4", "#23766fcc"), + Some(SyntaxForeground { dark: "#80cbc4".into(), light: "#23766fcc".into() }) + ); + for bad in ["80CBC4", "#80CBC", "#80CBC4;color:red", "url(x)", "var(--syn-rainbow-1)", "red", ""] { + assert_eq!(syntax_foreground(bad, "#23766f"), None, "{bad}"); + assert_eq!(syntax_foreground("#23766f", bad), None, "{bad}"); + } + let asked = range(0, 0, 2); + let colored = syntax_foreground("#80cbc4", "#23766f"); + let marks = vec![ + PluginSyntaxMark { range: asked, token: String::new(), foreground: colored.clone() }, + PluginSyntaxMark { range: asked, token: String::new(), foreground: None }, + ]; + let kept = filter_syntax_marks("hello", &[asked], marks); + assert_eq!(kept, vec![PluginSyntaxMark { range: asked, token: String::new(), foreground: colored }]); + } +} diff --git a/crates/ide-plugin/src/types.rs b/crates/ide-plugin/src/types.rs index 0218a2006a..c5497bbe6f 100644 --- a/crates/ide-plugin/src/types.rs +++ b/crates/ide-plugin/src/types.rs @@ -817,6 +817,54 @@ pub struct PluginInlayHint { pub padding_right: bool, } +/// One node of an editor syntax snapshot (`syntax-decorations-provider`). +/// `parent` indexes this same list. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyntaxNodeSnapshot { + pub name: String, + pub range: ide_core::Range, + pub parent: Option, +} + +/// A theme-token mark returned by one plugin. `plugin` is assigned by the host. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyntaxDecoration { + pub plugin: String, + pub range: ide_core::Range, + pub token: String, + /// Checked colours, `#rrggbb` / `#rrggbbaa` in lower case; painted instead of `token`. + pub foreground: Option, +} + +/// A mark's own foreground for dark and for light themes. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyntaxForeground { + pub dark: String, + pub light: String, +} + +/// A mark before the host has attached the plugin that produced it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PluginSyntaxMark { + pub range: ide_core::Range, + pub token: String, + pub foreground: Option, +} + +/// Answer of `plugin_syntax_decorations`. `stale` means the document changed +/// while the plugins were running; `marks` is then empty. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct SyntaxDecorationBatch { + pub version: u64, + pub epoch: u64, + pub stale: bool, + pub marks: Vec, +} + // ---- declarative views (wit/views.wit) --------------------------------------- #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] diff --git a/crates/ide-plugin/src/wit_host.rs b/crates/ide-plugin/src/wit_host.rs index 690dfe8ac0..5776cbf485 100644 --- a/crates/ide-plugin/src/wit_host.rs +++ b/crates/ide-plugin/src/wit_host.rs @@ -2682,6 +2682,13 @@ pub(crate) mod inlay_bindings { }); } +pub(crate) mod syntax_decoration_bindings { + wasmtime::component::bindgen!({ + world: "syntax-decorations", path: "../../wit", + with: { "openidea:plugin/types": super::bindings::openidea::plugin::types }, + }); +} + pub(crate) mod endpoints_bindings { wasmtime::component::bindgen!({ world: "endpoints", path: "../../wit", diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm index 1bfe6cae33..52965f7399 100644 Binary files a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources index 4d7de16cc5..3cb9bc4a0a 100644 --- a/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/api14/dist/plugin.wasm.sources @@ -1 +1 @@ -daf3ed46b1e98c6b416c0092a10a02579d2cf97959cedd03df1851a5e76d675d +fbb81178d7ee654ba2ba009253643bb3e13865c6f41b946ad39508145c481df0 diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm index 18fc6cd448..b8d946edb4 100644 Binary files a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources index 9b478445b4..7da9e15af9 100644 --- a/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/build-graph/dist/plugin.wasm.sources @@ -1 +1 @@ -b54f16ce7e7caf877ea464b50014117fc10f30b761236e5ddcb19ad07254ea13 +3a246151d713185ea416f72e1c4dacb6d46b0c68a48b878f131c517051e5823d diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm index 21ff58f54f..80a9c594a4 100644 Binary files a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources index 996f9469a1..040d5b3cc1 100644 --- a/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/clipboard/dist/plugin.wasm.sources @@ -1 +1 @@ -56e088be4df2db66a03060d388890ff9b68c354e36851ad46665b26bd27ea817 +c71fba2e8fc92e0c30b88b79e91a62e829d0e4651a4cee43fb91af6388f27688 diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm index bcbb4f0584..4396475532 100644 Binary files a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources index 2661e56120..7dd0471561 100644 --- a/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/commit/dist/plugin.wasm.sources @@ -1 +1 @@ -eefdb2d5e0b1fcf96d3ba03e5494513577f43f877d675873d4b922ee71bd3cc5 +c38fe66dd5601e29539cc002ea15ec9a33f70d0df129b6d3d2cb0da95358d632 diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm index af8dc374e7..81ceeaa3d6 100644 Binary files a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources index f6bd9577a7..31ec6ff432 100644 --- a/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/completion-list/dist/plugin.wasm.sources @@ -1 +1 @@ -00c70c0584a32dacdaee29379b805815d17e6d9cb209e1c21d72fbfc18020498 +c3fb87d8e3782fbe37dbdae67fefbaca9e11e97b9b34d92cc575e8f6dfcbe566 diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm index 1d2d5ce5cb..704f65ca28 100644 Binary files a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources index dded103ef7..8fd4910d3c 100644 --- a/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/data-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -e08f776a59706399eca922a324f21835208740a16c2e87911f0c338dd8e25cb2 +40f458ad646b1ecb4f68dcd190fcb6b979a07bbffcb63a136ba66eaa8bb90522 diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm index b236ae14d7..9ca253d1ee 100644 Binary files a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources index 0a56573ab1..7cdb8f7c37 100644 --- a/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/decorations/dist/plugin.wasm.sources @@ -1 +1 @@ -43bc34ad3aafd1d2869cf8f745dbaa0e8fce05ae6e39bf91ab39660cbcfc4740 +f72b332f4288f992ba0ad4d7732f2c52e9eb168222cd0b405afcc593946890d1 diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm index 475247d709..58bc8a173d 100644 Binary files a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources index 285b570ff0..8dba62dfa6 100644 --- a/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/detail-views/dist/plugin.wasm.sources @@ -1 +1 @@ -b4d92a22c5ebadc47284a22be1de2beec6deeffcc2f60c55173b924322588844 +74c63125ea431acea5f43e49c490c8810af342f476cffbe29f5fe567db4dbc30 diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm index 1ae0fb833b..10f216bc73 100644 Binary files a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources index f74d550bb2..f98a0fffc1 100644 --- a/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/diagnostics/dist/plugin.wasm.sources @@ -1 +1 @@ -452aed5f05ac3cc3d299afd74427fd58c5934dec6ca5a239e2a1e347ba036044 +e09c6b3e642f2bae0c86551a89c89a73f41d366d47f4b29768e21eaa879d9260 diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm index abb638a520..38030f5316 100644 Binary files a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources index 1888ee1c24..b37c0745ed 100644 --- a/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/endpoints/dist/plugin.wasm.sources @@ -1 +1 @@ -2abcea42de506e9e28a0970ba2a8615c7cc88d769cb5fa47fe3bb57e03af5258 +a77a9acf6b4003c24d2ef55f63d33f488eb7ae1205fb143b3fc57d723cec55bc diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm index 0b7912bf94..e835640b23 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources index 48832a9e2b..7ed5a1a23d 100644 --- a/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution-output/dist/plugin.wasm.sources @@ -1 +1 @@ -60e1a1925b3d83ea34be69727b9e8804ba3a1db767b7a06f87bcad6ab326a604 +82fdbc642d28863ca61f602b7df5c25b5553e70c9d90280d96b5ee71e9447400 diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm index 758a85a949..48550f04d3 100644 Binary files a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources index bc06e075b3..56262d93c5 100644 --- a/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/execution/dist/plugin.wasm.sources @@ -1 +1 @@ -92d626a131d5b8b82781a3cb7d87a293ddb0e5e81450bef17dc505c12f2a4f57 +eb250aaf92ff5f7efca010dfc9a2d3aee62b698390330bbbc75a2f10b9328989 diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm index 80f43dd499..4ae27bd69f 100644 Binary files a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources index c6dc598150..4b9e92cae7 100644 --- a/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/ext-owner/dist/plugin.wasm.sources @@ -1 +1 @@ -86ec4a4ebc1d770b0e6973d9169544111fce24485f3eed8b7040d7dce8280dcd +24ffd29881199bb7eede7084a4a11d14e70ee78e53261e2bd33d173112c98fd3 diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm index 74d8343038..648ee91ac9 100644 Binary files a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources index 14b3627f7b..367f4cb608 100644 --- a/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/file-templates/dist/plugin.wasm.sources @@ -1 +1 @@ -254dddbf9c67f00451fc173602532e2e4fe92a6fd8d3d91824c950a403c7583c +740183f685319af40013c81a26da70df23e9a9fbe9293c24605c55b1cf6a9f55 diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm index c66d4aa57a..38016774de 100644 Binary files a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources index 320d9d9035..afbf7d705d 100644 --- a/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/files-events/dist/plugin.wasm.sources @@ -1 +1 @@ -49e66ff2b91e070477c272ac1c5c60367148b274d75bb7d92efca0b1d5092f6a +ba325d0dab1366018feef26a7bd5a8f2002f946972e725c1df10f2ffb7a0ab8e diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm index fc20057cb8..7e6c9b9b2f 100644 Binary files a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources index a8bd9832c3..951825f550 100644 --- a/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/grouped-views/dist/plugin.wasm.sources @@ -1 +1 @@ -cfb61fe65b344d86bf71a821c1216963d9ab7789206a292450b1d66222d6cbc5 +3b1f0a3a43f0e0a6f17dd0d648ce69cf0619f052a981958656b1065c4923b4ec diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm index 677e13359c..dbe2f6c84c 100644 Binary files a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources index 23f771220f..77f7ff7b3c 100644 --- a/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hello/dist/plugin.wasm.sources @@ -1 +1 @@ -706e69379855967f598abbcc3bcc955cb5581ca4b009d5220f4785ccb05dda0f +d9e930f460de8bb20f5b228e5e15191b0a27c1247d564e5595b976f5453050ea diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm index 016cdafe09..e0db29c402 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources index 217e1d6e2c..3a040e1703 100644 --- a/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm.sources @@ -1 +1 @@ -118c6f4870e99d57acfc9fbb265031a3a7d1dfc03b4408be8c8b5eade33e4f38 +fd510b30360542de87a80052f373ad9b98faa68bc8c267bf1845d44d21e0fde7 diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm index 92def6f8ee..49dd5a24ca 100644 Binary files a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources index ee87125cd5..4c09423b1d 100644 --- a/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/hover/dist/plugin.wasm.sources @@ -1 +1 @@ -19b04c02c5230c0700bdc8fe8a3cae266422aa23e8d7e932b7dafd546e41846d +c646af70d26715a3c231c80e16d93e40b8a2570516322c364924854be08af1d7 diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm index d3b36052c2..46fbca1f14 100644 Binary files a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources index 9350ea10cd..abdba270d7 100644 --- a/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/indexer/dist/plugin.wasm.sources @@ -1 +1 @@ -14e46bbf68efaacaff75627814be666dcf00460656ba7e66b7fb088317ce6c79 +1f64dbc8b9f1d623080eda6b19fccc161f35c9801e5c1689abb2a8e993f4856e diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm index 0a44231d65..fc94c5fe4b 100644 Binary files a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources index c070bcab7c..60e2ebd753 100644 --- a/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/inlay-hints/dist/plugin.wasm.sources @@ -1 +1 @@ -55afdbdb4db919c59a38b14eb6483c911934d64d433ef19106098bfde4830a91 +71826d403bdaf5fee4390c0eb7a9fed7ee6804742b4c23ea8607e4897d6f5cce diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm index 1dafc33985..e2751530f8 100644 Binary files a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources index ae825c4963..a0decb60cf 100644 --- a/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/jobs/dist/plugin.wasm.sources @@ -1 +1 @@ -99099a7f01295188bade661777d926fd12ba434ec4ff36035ee1b13523d63ae8 +418b35d6a7e98fe80d9594af073b409cf400ab8b65a7d2f42b524edceb284de4 diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm index 41472ecd5d..9d6ac4b7dd 100644 Binary files a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources index c8de6f86f1..a6eb7499d7 100644 --- a/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/language-features/dist/plugin.wasm.sources @@ -1 +1 @@ -ff6ecc3baa94d7cd4447f3d9f2a3f819ee44dac3564fdfba3a5f88a0637c0af0 +185a50ea6cd0564cb73ee66cd700b0dc052a1eab0c4418bfc515de83c7f88c55 diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm index a51fba83ef..7213000b76 100644 Binary files a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources index 505503fffb..3932ec9fff 100644 --- a/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/lsp-requests/dist/plugin.wasm.sources @@ -1 +1 @@ -45990bb70318e04cb69c8ffa5c980b85e65bd860559b10507061762f8ecb38b3 +9024a4e059a4a5b5fa0c92bd235671914db911971f66d1189c34845c08c905e0 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm index faad1a731a..ee24ef2a46 100644 Binary files a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources index 69dfcd17d6..ad982e2e9d 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/misbehave/dist/plugin.wasm.sources @@ -1 +1 @@ -cb21ced740ff159017a96075e41b31782c062db10596e4286327fb4d002b6ebf +20f7450b91e444e74354bf87c1e7fdddaccdd500e6a2c315d622bcff45086066 diff --git a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs index e00f52fc27..7f367b56af 100644 --- a/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs +++ b/crates/ide-plugin/tests/fixtures/misbehave/src/lib.rs @@ -8,6 +8,7 @@ wit_bindgen::generate!({ include openidea:plugin/plugin-syntax@1.20.0; export openidea:plugin/providers@1.20.0; export openidea:plugin/file-actions@1.20.0; + export openidea:plugin/syntax-decorations-provider@1.20.0; } ", path: "../../../../../wit", @@ -512,4 +513,29 @@ impl exports::openidea::plugin::file_actions::Guest for Misbehave { } } +/// The first node's name selects the failure: `panic`, `spin`, or `sleep:`. +/// A normal name returns no marks, so a well behaved plugin beside this one +/// still supplies its own. +impl exports::openidea::plugin::syntax_decorations_provider::Guest for Misbehave { + fn syntax_decorations( + request: exports::openidea::plugin::syntax_decorations_provider::DecorationRequest, + ) -> Vec { + if let Some(name) = request.nodes.first().map(|node| node.name.as_str()) { + if name == "panic" { + panic!("boom"); + } else if name == "spin" { + loop { + std::hint::black_box(0); + } + } else if let Some(ms) = name.strip_prefix("sleep:").and_then(|n| n.parse::().ok()) { + let until = std::time::Instant::now() + std::time::Duration::from_millis(ms); + while std::time::Instant::now() < until { + std::hint::black_box(0); + } + } + } + Vec::new() + } +} + export!(Misbehave); diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm index 1e2d6e6cb7..250d1051b2 100644 Binary files a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources index 1fa64d7847..25a3ba7a6e 100644 --- a/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/net-setting/dist/plugin.wasm.sources @@ -1 +1 @@ -9bdc92f81b7985bec88bd2b3929771df22f1d31945e575a3a71ca705aad4d1dc +800d5114110774f24ddd30cf4b4b14a802dc9f41cdc5e8834a4a429adc186ed3 diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm index cda86bde40..49353c8ec1 100644 Binary files a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources index b8541d8b73..f4fd568240 100644 --- a/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/path-events/dist/plugin.wasm.sources @@ -1 +1 @@ -3cbfd56bef0062d1fb25854efe256c34c7de23ddf1ae4611e05119410a487f4b +aab5a3b60e1f0dfc3474994f8d61b571b1a15b5070ee753d75234fac300843bc diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm index 60ac434ecf..6a504d0c99 100644 Binary files a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources index f3e7c787e9..0f2b191ded 100644 --- a/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/private-dir/dist/plugin.wasm.sources @@ -1 +1 @@ -87c9742d4700629243bbfd544d227c64bbb478a0607bd21b1a16072eb50b6b8e +3e6345dee4360f925168f1a9dca30e9464054937252aa075368d5b3fed237c62 diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm index db3700ff77..a15305cb7e 100644 Binary files a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources index 434b616c6b..f032744609 100644 --- a/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/run-anything/dist/plugin.wasm.sources @@ -1 +1 @@ -8bdf895f76e7615b03cd8d2e50ee8272e9598a6f21426a4ec86e124fbaf86741 +97d5c95eff3e2d5837f7ff07f7f4c82dfbbdec3522b8294d0a865e70ae020d14 diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm index 70985baf38..41d5f5355d 100644 Binary files a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources index 69c72a0082..1d60dd388b 100644 --- a/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/search/dist/plugin.wasm.sources @@ -1 +1 @@ -63cc4ad099d6c383b78e46dddc5b578c899cfc42e4b9dc5726704f1d6c8da83a +fd34c1b1d1a131122822a102d9168b1c700b5f26c1a336a2bda0ae07b1d83314 diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm index 9c9f847032..1b1c9e285b 100644 Binary files a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources index 30936e80d2..19936245eb 100644 --- a/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/semantic-tokens/dist/plugin.wasm.sources @@ -1 +1 @@ -213bdb00682f6e573f54ad07698e5090f9bc1ccd3ebfc9cf7f703b2fdce9f30a +20d01f5aa6f3519f40138a674500d5485a87bd2ba83e91b584e7e7592801fe86 diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm index d83d709a56..138600a39d 100644 Binary files a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources index ea1bf4e4fe..0ca312fda5 100644 --- a/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/settings-pages/dist/plugin.wasm.sources @@ -1 +1 @@ -1facc9f2d4e26f87e8a80719b560b61d7e6a3c953753cfe20bc2eba9b31934d1 +da1cabc8d502e54bc4dbcaa92a8b8d570d696b842dba174f3e0011db896d9083 diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm index 67efd80a3d..7508e7a1f9 100644 Binary files a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources index 932b06cb54..43b75c92e9 100644 --- a/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/storage/dist/plugin.wasm.sources @@ -1 +1 @@ -7fbe4b0ac9d49efd8300867d9b447bced49a7f3d9ab7bcebd74b11c7c8ff546f +911a05d11ca6e419fd7adee7a21fa76cb669a2d32242c281f59eb6366a55810d diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm index 0fcf5aa9ac..8ab8c1a206 100644 Binary files a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources index 2adbaeb77d..5d9b48195c 100644 --- a/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/symbols/dist/plugin.wasm.sources @@ -1 +1 @@ -2c4cc949885b3d1d0f4a9dbc44c239d55ed4e43f71c8b09a8da3e9f31a439841 +039e8c3424f0417b1cd8cd46b2d2e2938971304983b61e9bc5e8ce4955ab96cd diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.lock b/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.lock new file mode 100644 index 0000000000..8386541680 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.lock @@ -0,0 +1,336 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", + "serde", + "serde_core", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "macro-string" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e7b3a5bbb2f63aaa223a671ea1bd0e7bc16bd30ce387324cf63995deaddbbd2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "openidea-plugin" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "wit-bindgen", +] + +[[package]] +name = "openidea-test-syntax-decorations" +version = "0.1.0" +dependencies = [ + "openidea-plugin", +] + +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "wasm-encoder" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4495a6f85dd94c411c749303efcbc5defade0b0cbdbc0541495241ab917a9b5a" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c86ff6668190d9fb70372b306b4f9fe8930f0e2f57ce72e4922bf2f117900949" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasmparser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "974d643b125b272607e2fff8012ea14a8328acd7621e4bafa7afb32500052b1b" +dependencies = [ + "bitflags", + "hashbrown", + "indexmap", + "semver", +] + +[[package]] +name = "wit-bindgen" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b85a987ab61d365382d25c7d47e26edd48941b3bf6e3fbf76eff918bc71dab06" +dependencies = [ + "bitflags", + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen-core" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "775e122e390603abfacd548027016cd0113a6e2bf2f8ce6bdd3658b013456ea8" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84e26e13b9d972026778d2ffb7985736de116026fdc8d9464f966e12df2eb240" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.63.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a008a0d6b4840677326beb4edbeb210a2f1b7d0183fb7cc33f466b90fd7fb6" +dependencies = [ + "anyhow", + "macro-string", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078def49fdb49cab405c3006e05793b3fdaf7069126ba6b9c97d01ec8c98fe4c" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.262.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00f0dc051466ffe46787721fca3d088536f158ae400be044f1b1c386ba9397ad" +dependencies = [ + "anyhow", + "hashbrown", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-ident", + "wasmparser", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.toml b/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.toml new file mode 100644 index 0000000000..a90ce57e71 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "openidea-test-syntax-decorations" +version = "0.1.0" +edition = "2024" +publish = false + +[workspace] + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +openidea-plugin = { path = "../../../../../sdk/rust/openidea-plugin" } + +[profile.release] +opt-level = "s" +lto = true +strip = true +codegen-units = 1 +panic = "abort" diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/README.md b/crates/ide-plugin/tests/fixtures/syntax-decorations/README.md new file mode 100644 index 0000000000..7c1cb8bf43 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/README.md @@ -0,0 +1,5 @@ +# Syntax decorations fixture + +Proves the `syntax-decorations` provider. It is not a highlighter: the first +syntax node that has a parent is marked `rainbow-1`, and a document version of +0 returns nothing. diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm new file mode 100644 index 0000000000..6b7117474d Binary files /dev/null and b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources new file mode 100644 index 0000000000..1fd1e7dba6 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/dist/plugin.wasm.sources @@ -0,0 +1 @@ +7bc77abc900cd575e24e2fda4a27aac752b82df45811671aeaef3736dafa2808 diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/plugin.toml b/crates/ide-plugin/tests/fixtures/syntax-decorations/plugin.toml new file mode 100644 index 0000000000..cf22a3a125 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/plugin.toml @@ -0,0 +1,12 @@ +id = "test.syntax-decorations" +name = "Syntax decorations fixture" +version = "0.1.0" +engines.openidea = "^1.20" +wasm = "dist/plugin.wasm" + +[capabilities] +required = ["editor.read"] + +[[contributes.providers]] +kinds = ["syntax-decorations"] +languages = ["javascript"] diff --git a/crates/ide-plugin/tests/fixtures/syntax-decorations/src/lib.rs b/crates/ide-plugin/tests/fixtures/syntax-decorations/src/lib.rs new file mode 100644 index 0000000000..6f1e2631e5 --- /dev/null +++ b/crates/ide-plugin/tests/fixtures/syntax-decorations/src/lib.rs @@ -0,0 +1,36 @@ +use openidea_plugin::syntax_decorations::{SyntaxDecorationRequest, SyntaxDecorations, SyntaxMark}; +use openidea_plugin::{Error, Invocation, Plugin, register_plugin}; + +#[derive(Default)] +struct Fixture; + +impl Plugin for Fixture { + fn run_command(&mut self, id: &str, _: &Invocation, _: Option<&str>) -> Result, Error> { + Err(Error::NotFound(id.into())) + } +} + +impl SyntaxDecorations for Fixture { + fn syntax_decorations(&mut self, request: &SyntaxDecorationRequest) -> Vec { + if request.document.version == 0 { + return Vec::new(); + } + // Version 7 asks for colour marks: one valid, one the host must drop. + if request.document.version == 7 { + let Some(node) = request.nodes.iter().find(|node| node.parent.is_some()) else { return Vec::new() }; + return vec![ + SyntaxMark::colored(node.range, "#80CBC4", "#23766f"), + SyntaxMark::colored(node.range, "#80CBC4;color:red", "#23766f"), + ]; + } + request + .nodes + .iter() + .find(|node| node.parent.is_some()) + .map(|node| SyntaxMark::new(node.range, "rainbow-1")) + .into_iter() + .collect() + } +} + +register_plugin!(Fixture, syntax_decorations); diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm index e1ae870ebe..19c689a7ec 100644 Binary files a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources index 4ca0325e29..549ee7ed09 100644 --- a/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/tables/dist/plugin.wasm.sources @@ -1 +1 @@ -23c9187f4deb89351de32a52e8f08b4933d2bbe72fcf3c9a7c9b29ae20bbdb44 +d1f97800b9aad4b6c27d2a2e1e47dfa1ca70741b9a4163940d36547a2a2d5af1 diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm index 1702ecdf88..1ff53e3890 100644 Binary files a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources index 97ca43e3a0..c94219830b 100644 --- a/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/watch-paths/dist/plugin.wasm.sources @@ -1 +1 @@ -e7159f2069bbfbdb68b8770040772949013b733e16513d57333664d6a945a326 +671ed8fe2f6a922fd92ee3ca2a6c2e47ffcf0985fb9e4f96c5ec7712d3c728e6 diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm index 09d1a4b559..3c5d4f47a7 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources index 14395bcbb6..189e197b48 100644 --- a/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-content/dist/plugin.wasm.sources @@ -1 +1 @@ -29f64f3236c46cd1b0e7915736fdb41f3826161c4d950aac7ed7b6b0767786be +5cd36ce9a7e01aafadd4b14fab1367664a7a5ffa0f7332d8b3b22770bb381422 diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm index a805d17bb5..177463ff4a 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources index 4ad9d777fb..cb2354a49f 100644 --- a/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-log/dist/plugin.wasm.sources @@ -1 +1 @@ -072c75538a1e36064fafd69f66e7d40024b4f5909f3d6acf8191071dbe195c92 +da9ee39b1b46ab778b0bf6b5d3719d5d0ef5500778be75ff54ca276b31310ac2 diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm index 98c4b950fc..3b346dd7b0 100644 Binary files a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm and b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm differ diff --git a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources index 35ea2bc0e5..8a0113c3aa 100644 --- a/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources +++ b/crates/ide-plugin/tests/fixtures/web-pty/dist/plugin.wasm.sources @@ -1 +1 @@ -ecc4f6f73209bd2d4d10353ed73a3a8629381cf6c8901673ae8ce19541136b96 +f81c21c6cfe046bf2149f53bee39aeb45b320593996e163f4e5ea3acfebdfa78 diff --git a/docs/en/plugins/versioning.mdx b/docs/en/plugins/versioning.mdx index 6c399d5a62..9e842b5114 100644 --- a/docs/en/plugins/versioning.mdx +++ b/docs/en/plugins/versioning.mdx @@ -34,7 +34,7 @@ The plugin API has one version number: the version of the WIT package in [`wit/` | 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`: editor decorations with their own `#rrggbb` / `#rrggbbaa` foreground and background, for colors outside the theme palette | | 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`: a package web page floating over the workbench that never takes the keyboard focus, placed and resized through `openidea.overlay`; `[[contributes.dialogs]]`: a package web page in a modal, resizable IDE dialog opened with `views.reveal`, with a `closed` view event and `openidea.dialog.close()`; `events.subscribe-paths-with-options` (`debounce-ms`), `workspace.project.generation` and `FilesChanged` project/generation fields, stale run target/configuration rejection, and the `project-closed` lifecycle event; `execution-configurations`, `run.start-with-options` and `runDetectors.outputMode`: `pipes` or `pty` console output for plugin run configurations; `[[contributes.runAnything]]` with the `run-anything-provider` export: Run Anything lines starting with the plugin's prefix; `views.open-terminal-session-in`: a keyed terminal in a project directory; `workspace.invoking-project`: the project of the window a call serves, also in `gutter-actions` and `hover-actions`; `events.watch-paths` and the `watched-files-changed` event: files and directories outside the project, within `fs.read` grants; the `run-configuration-completion` export: completion in the Arguments field of the plugin's own run configurations; `services.context` and `services.toolbar` menus on the IDE's own Services nodes, with the selected services as the command argument; `executor` on `[[contributes.javaAgents]]`: "Run/Debug '' with " beside Run and Debug, the only launches that get that agent, also startable from the plugin's own commands with a configuration id; grant-scoped `agents.fork-session`: fork a recorded native agent session (`claude`, `codex`, or `copilot`) into a new task in the invoking window's project (`agents` capability), with the host validating the session and building the fork invocation itself | | 1.19.0 | In development on `main` | `[capabilities.reasons]`: the plugin's own sentence on why it asks for a capability, shown below the host's description in the permission dialog and Settings › Plugins; `settings.open` / `settings.open-permissions`: open Settings at one of the plugin's own pages or at its permissions; `net.fetch-stream`: a response whose body is read as it arrives (server-sent events, streamed model replies), with the SDK's `host::fetch_stream` and `sse` parser; `editor.open-as-text`: open a file in the built-in text editor even when a custom editor claims it (the SDK's `host::open_editor_as_text`); the `openIn` menu: the **Open In** submenu of the editor, its tab and the Project view | -| 1.20.0 | In development | Database table context menus and read-only table schema inspection (`database.schema`). | +| 1.20.0 | In development | Database table context menus and read-only table schema inspection (`database.schema`). Optional `syntax-decorations-provider` export: foreground marks on an open text editor, in the theme tokens `rainbow-1` … `rainbow-5` or its own `#rrggbb` colours for dark and light themes, and a bounded slice of the editor's syntax tree. | The full list of what each version added is in [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md). diff --git a/docs/zh/plugins/versioning.mdx b/docs/zh/plugins/versioning.mdx index 54b26c2577..6c1d502703 100644 --- a/docs/zh/plugins/versioning.mdx +++ b/docs/zh/plugins/versioning.mdx @@ -31,7 +31,7 @@ description: "engines.openidea、插件 API 从 1.0 到 1.20 的各个版本, | 1.17.0 | OpenIDEA 0.1.53 | `decorations.set-styled`:自带 `#rrggbb` / `#rrggbbaa` 前景色和背景色的编辑器装饰,用于主题调色板之外的颜色 | | 1.18.0 | OpenIDEA 0.1.54 | `[[contributes.overlays]]`:悬浮在工作台上方、从不抢占键盘焦点的插件网页,可通过 `openidea.overlay` 移动和调整大小;`[[contributes.dialogs]]`:插件网页显示在可调整大小的模态对话框中,用 `views.reveal` 打开,关闭时发 `closed` 视图事件,页面可调用 `openidea.dialog.close()`;`events.subscribe-paths-with-options`(`debounce-ms`)、`workspace.project.generation` 与 `FilesChanged` 的 `project`/`generation` 字段、过期运行目标/配置拒绝以及 `project-closed` 生命周期事件;`execution-configurations`、`run.start-with-options` 与 `runDetectors.outputMode`:插件运行配置的控制台输出方式(`pipes` 或 `pty`);`[[contributes.runAnything]]` 与 `run-anything-provider` 导出:以插件前缀开头的 Run Anything 行;`views.open-terminal-session-in`:在项目子目录中打开带 key 的终端;`workspace.invoking-project`:本次调用所服务窗口的项目,`gutter-actions` 和 `hover-actions` 中也可用;`events.watch-paths` 与 `watched-files-changed` 事件:监听项目之外、`fs.read` 授权范围内的文件和目录;`run-configuration-completion` 导出:补全插件自己运行配置的“实参”字段;`services.context` 和 `services.toolbar` 菜单:作用于 IDE 自带的 Services 节点,命令参数是选中的服务;`[[contributes.javaAgents]]` 的 `executor`:运行和调试旁边的“使用 <title> 运行/调试 '<name>'”,只有经它启动时才加载该代理,插件自己的命令也可用配置 id 经它启动;需授权的 `agents.fork-session`:把录制的原生 agent 会话(`claude`、`codex` 或 `copilot`)派生为调用窗口项目中的新任务(`agents` 能力),宿主自行校验会话并构造 fork 调用 | | 1.19.0 | `main` 上开发中 | `[capabilities.reasons]`:插件用一句话说明为什么需要某个能力,显示在授权对话框和 设置 › 插件 中宿主说明的下方;`settings.open` / `settings.open-permissions`:打开设置并定位到插件自己的页面或它的权限;`net.fetch-stream`:边到达边读取响应体(服务器推送事件 SSE、模型的流式回复),SDK 提供 `host::fetch_stream` 和 `sse` 解析器;`editor.open-as-text`:即使文件被自定义编辑器认领,也用内置文本编辑器打开(SDK 的 `host::open_editor_as_text`);菜单点 `openIn`:编辑器、标签页和项目视图的 **打开方式** 子菜单 | -| 1.20.0 | `main` 上开发中 | Database table context menus and read-only table schema inspection (`database.schema`). | +| 1.20.0 | `main` 上开发中 | 数据库表的上下文菜单和只读表结构查看(`database.schema`)。可选的 `syntax-decorations-provider` 导出:用主题 token `rainbow-1` … `rainbow-5` 或自带的深色/浅色主题 `#rrggbb` 颜色,给打开的文本编辑器中的范围涂前景色,依据编辑器语法树的有界片段。 | 每个版本新增内容的完整列表见 [`plugins/README.md`](https://github.com/l0ng-ai/openidea/blob/main/plugins/README.md)。 diff --git a/plugins/README.md b/plugins/README.md index e04d416218..bf194ac382 100644 --- a/plugins/README.md +++ b/plugins/README.md @@ -33,10 +33,10 @@ plugins/ ├─ regex-tester/ # html view talking to its code, settings, the editor's selection └─ license-header/ # file-opened events, quick fix, project scan in a task sdk/rust/openidea-plugin/ # the Rust SDK (host API, Plugin trait, mock host) -crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints, decorations +crates/ide-plugin/tests/fixtures/ # test plugins: hello, jobs, language-toy, misbehave, semantic-tokens, hover, commit, inlay-hints, decorations, syntax-decorations ``` -The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.19.0`, world +The plugin API is defined in [`wit/`](../wit/) (`openidea:plugin@1.20.0`, world `plugin`). ## 1. Quick start @@ -1313,6 +1313,13 @@ cancellable, bounded by the I/O timeout and limited to 4096 entries per collecti See the [database guide](../docs/en/plugins/guides/database.mdx) for a complete manifest and Rust example; generating files additionally requires `project.write`. +### Syntax decorations (API 1.20) + +With `engines.openidea = "^1.20"`, a plugin can paint foreground marks from the +editor's own syntax tree. Declare `syntax-decorations` and register +`register_plugin!(MyPlugin, syntax_decorations)`. The host asks; the plugin does +not parse. See [Syntax decorations](#syntax-decorations). + ### Database sources (API 1.4) Declare `database.sources` (medium risk). All five calls require it and a @@ -1919,6 +1926,117 @@ shows it. The host asks the language server and the plugins together, under the edit-path budget, and shows both; the editor asks again after edits and scrolling. Labels are cut at 256 bytes and tooltips at 1 KiB. +#### Syntax decorations + +The `syntax-decorations` kind (API 1.20) paints a foreground colour on ranges of +an open editor. It is how a plugin can colour syntax — for example keys at +different depths — using the colours of the active theme. Register with +`register_plugin!(MyPlugin, syntax_decorations)` and implement +`openidea_plugin::syntax_decorations::SyntaxDecorations`: + +```rust +impl SyntaxDecorations for MyPlugin { + fn syntax_decorations(&mut self, request: &SyntaxDecorationRequest) -> Vec<SyntaxMark> { + let Some(node) = request.nodes.iter().find(|n| n.parent.is_some()) else { + return vec![]; + }; + vec![SyntaxMark::new(node.range, "rainbow-1")] + } +} +``` + +```toml +[capabilities] +required = ["editor.read"] + +[[contributes.providers]] +kinds = ["syntax-decorations"] +languages = ["yaml"] +``` + +The [syntax decorations test plugin](../crates/ide-plugin/tests/fixtures/syntax-decorations) +demonstrates the provider on JavaScript. + +The host sends one `SyntaxDecorationRequest` for the ranges it is painting +and a bounded syntax snapshot of at most 8192 nodes. Visible ranges are added +first. Sticky header lines, which can sit outside the viewport, are added +after them and only while the request still has room. A request holds at most +32 ranges. When the visible ranges already fill that budget, a sticky header +is left out and keeps the syntax highlighter's colour. + +Each node has the parser's `name`, a UTF-16 `range`, and `parent` as an index +into that same list, or none. Index 0 is a real node. The list is ordered by +position, so a parent index may be greater than the child's index. The +snapshot contains the nodes that overlap the requested ranges and the +ancestors needed to reach them, until the node budget runs out. It can be a +partial tree: the editor does not parse the rest of the file for the plugin, +and the host does not run a second parser. `parent` is none when that ancestor +was not included. None does not mean the node is the root of the real tree; +truncation can drop an ancestor and keep the child. Node names belong to the +editor's parser. They are not a vocabulary shared by every language, and a +plugin must not treat a name as stable across parsers. + +`document.version` is the host buffer version when the call starts. A result +whose document changed before the call finished is discarded. The editor also +discards a result when the viewport, the syntax tree or the document moved +while the plugin was running, and it does not ask again for a selection change +alone. Edits, scrolling, folding, syntax updates, enabling the plugin and +plugin setting changes ask again. A theme change does not. Rainbow tokens +are theme variables, and a mark's own colours already cover both kinds of theme. + +A mark is either a token or its own colours. The tokens `rainbow-1`, +`rainbow-2`, `rainbow-3`, `rainbow-4` and `rainbow-5` map onto the existing +`--syn-rainbow-1` … `--syn-rainbow-5` colours of the light and dark themes. For +colours outside that palette, set `foreground` (`SyntaxMark::colored` in the +Rust SDK): `#rrggbb` or `#rrggbbaa` for dark themes and for light themes, the +same colour format as `decorations.set-styled`. The host drops a mark with an +unknown token or an invalid colour; a plugin cannot send CSS, HTML, a script, a +class name or a theme variable. The mark changes the foreground only; font weight +and style stay as they are. The editor stylesheet, not the plugin, picks the dark +or light colour when the theme changes. The mark is drawn inside the syntax highlighter's span, so it overrides that +span's foreground colour. Existing +`decorations.set` and `decorations.set-styled` sets are unchanged and stay on +their own layer. Where a syntax-decoration mark covers the same characters, +its foreground is the inner one, so it wins over a `set-styled` colour; a +background or underline from `set-styled` still shows. + +The host sends a snapshot only to plugins with an `editor.read` grant that +declared the document's language. The document must be open in the calling window. A +project plugin still only receives documents inside the project where it was +granted. The plugin cannot ask for a different document. Ranges outside the +document or outside the requested ranges, a parent index that does not point +at a node in the list, and more than 10,000 marks are dropped. One plugin's +marks never replace another's. When several plugins mark the same range, declaration +order is kept and the earlier plugin's mark is the inner span, so its colour +is the one that shows. Ranges that only partly overlap are split where they +meet. Each plugin keeps the characters only it covers, and the shared +characters are nested. Plugin id does not decide that case. + +The editor waits 50 ms and syncs pending edits before sending one request +for the latest snapshot. A new refresh or a closed editor cancels a pending +or in-flight request. Calls use the editor-provider deadline (normally 50 ms +soft / 500 ms hard) and the same fuel and memory limits as other providers. +The editor discards answers superseded by a document, viewport, syntax tree +or provider change. Disabling or uninstalling a plugin +stops its actor, which drops a call that actor was still running; other +plugins' answers in the same request are kept. A timeout, a trap or an invalid +answer contributes no marks. Disabling, uninstalling or unloading the plugin +removes its marks. An answer already in flight is not applied after the plugin +set changes. Closing the editor drops the marks with the editor, and a +response that arrives after the editor is gone is ignored. An idle reclaimed +instance is asked again on the next refresh; its previous marks stay until +that answer arrives. A document the editor opened as past the code insight +file size limit is not sent. That limit is the user's Editor setting (1–50 +MiB, 5 MiB by default), decided when the document was opened. There is no +separate fixed character ceiling. + +The provider runs in the text editor. The diff viewer and notebook cells do +not ask it. + +Plugins built for an older API keep working. `set`, `set-markdown` and +`set-styled` are unchanged. A component that does not export +`syntax-decorations-provider` is not called. + #### Additional language features (API 1.4) Declare the following kinds under `[[contributes.providers]]`, with diff --git a/plugins/official/ai-completion/dist/plugin.wasm b/plugins/official/ai-completion/dist/plugin.wasm index b76d6edfca..6f9810dfe8 100644 Binary files a/plugins/official/ai-completion/dist/plugin.wasm and b/plugins/official/ai-completion/dist/plugin.wasm differ diff --git a/plugins/official/ai-completion/dist/plugin.wasm.sources b/plugins/official/ai-completion/dist/plugin.wasm.sources index 253a5cf12f..5cf00e7b4e 100644 --- a/plugins/official/ai-completion/dist/plugin.wasm.sources +++ b/plugins/official/ai-completion/dist/plugin.wasm.sources @@ -1 +1 @@ -4b1f2303c8b795c11e9c6c57d980005e28b0bdf53a98999175db0d573b38554f +55181617e0c0df5d3d454bf9cc95323f406ef247df09b43a25e06fd539393754 diff --git a/plugins/official/blame-annotations/dist/plugin.wasm b/plugins/official/blame-annotations/dist/plugin.wasm index 41b96b13df..c13a506db1 100644 Binary files a/plugins/official/blame-annotations/dist/plugin.wasm and b/plugins/official/blame-annotations/dist/plugin.wasm differ diff --git a/plugins/official/blame-annotations/dist/plugin.wasm.sources b/plugins/official/blame-annotations/dist/plugin.wasm.sources index accba9079d..64eb28e673 100644 --- a/plugins/official/blame-annotations/dist/plugin.wasm.sources +++ b/plugins/official/blame-annotations/dist/plugin.wasm.sources @@ -1 +1 @@ -3cabfcb916565d4ba98e10c1d935ecd8771e03eade5586a03a387e728d14ae68 +77fc141a21a9eecc7cf4eb6b4a5b88b79ef242f5e3eacbd150640e6f45038e3e diff --git a/plugins/official/checkstyle/dist/plugin.wasm b/plugins/official/checkstyle/dist/plugin.wasm index d791651db5..1c85e249e3 100644 Binary files a/plugins/official/checkstyle/dist/plugin.wasm and b/plugins/official/checkstyle/dist/plugin.wasm differ diff --git a/plugins/official/checkstyle/dist/plugin.wasm.sources b/plugins/official/checkstyle/dist/plugin.wasm.sources index 589564876c..d6e2c5fd7b 100644 --- a/plugins/official/checkstyle/dist/plugin.wasm.sources +++ b/plugins/official/checkstyle/dist/plugin.wasm.sources @@ -1 +1 @@ -c3dc2b4a769b65efc2958bcceed0249e3fa999f2592441fdf92338d7be61397a +7671635ca020d4ae590359dee691068a23449d75ec553fc9b265dccdaa0fa684 diff --git a/plugins/official/container-runner/dist/plugin.wasm b/plugins/official/container-runner/dist/plugin.wasm index f5dcb79e0c..81a4b5542f 100644 Binary files a/plugins/official/container-runner/dist/plugin.wasm and b/plugins/official/container-runner/dist/plugin.wasm differ diff --git a/plugins/official/container-runner/dist/plugin.wasm.sources b/plugins/official/container-runner/dist/plugin.wasm.sources index d10e2e0542..ce6688e02a 100644 --- a/plugins/official/container-runner/dist/plugin.wasm.sources +++ b/plugins/official/container-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -22d0cf6590e46fb79d2bd92ab9ef1939d5d7babb0ff7d8d236b62878b6443ade +277fc281b3fa914d9fee2d002e911d06a4f0f3a9e918c5ea1ae9298fdb807b66 diff --git a/plugins/official/csv-editor/dist/plugin.wasm b/plugins/official/csv-editor/dist/plugin.wasm index b5f02081ec..2a0504cad6 100644 Binary files a/plugins/official/csv-editor/dist/plugin.wasm and b/plugins/official/csv-editor/dist/plugin.wasm differ diff --git a/plugins/official/csv-editor/dist/plugin.wasm.sources b/plugins/official/csv-editor/dist/plugin.wasm.sources index 3e2b39fba9..3ed64398f9 100644 --- a/plugins/official/csv-editor/dist/plugin.wasm.sources +++ b/plugins/official/csv-editor/dist/plugin.wasm.sources @@ -1 +1 @@ -1e9d095de03a7c60a820a88407b384188b55f79d2a231b613e9b8b03c20387b1 +ee3eb799c9966c2c80bb7ad424d3121367caa9417568a65f854bc8d49f307e29 diff --git a/plugins/official/git-toolbox/dist/plugin.wasm b/plugins/official/git-toolbox/dist/plugin.wasm index e6e4cff350..998602f79a 100644 Binary files a/plugins/official/git-toolbox/dist/plugin.wasm and b/plugins/official/git-toolbox/dist/plugin.wasm differ diff --git a/plugins/official/git-toolbox/dist/plugin.wasm.sources b/plugins/official/git-toolbox/dist/plugin.wasm.sources index c43dd57215..2a67bd8afc 100644 --- a/plugins/official/git-toolbox/dist/plugin.wasm.sources +++ b/plugins/official/git-toolbox/dist/plugin.wasm.sources @@ -1 +1 @@ -013d920f8aaad0ebb44d1a11ef50d27aaedd0614241ce7be4f50eac9e996f986 +ad06ac2e49390bd719d9f76e47960f7b31c9811cf1c1e3188f8f9f08cfb8e872 diff --git a/plugins/official/graphviz/dist/plugin.wasm b/plugins/official/graphviz/dist/plugin.wasm index c5c74e310d..b1b9606c47 100644 Binary files a/plugins/official/graphviz/dist/plugin.wasm and b/plugins/official/graphviz/dist/plugin.wasm differ diff --git a/plugins/official/graphviz/dist/plugin.wasm.sources b/plugins/official/graphviz/dist/plugin.wasm.sources index 86ea98e436..1135d06e3b 100644 --- a/plugins/official/graphviz/dist/plugin.wasm.sources +++ b/plugins/official/graphviz/dist/plugin.wasm.sources @@ -1 +1 @@ -f6f54d8c8416bf5d2ab7da51614c044ba3252964ab913c49dfb09c9e6604f750 +aa241f27cced5c3aee46c4818a9a9d8649fe0b9aa6c9def7404a74a0135ed02b diff --git a/plugins/official/key-promoter/dist/plugin.wasm b/plugins/official/key-promoter/dist/plugin.wasm index 6dd6481cca..3253b9ae08 100644 Binary files a/plugins/official/key-promoter/dist/plugin.wasm and b/plugins/official/key-promoter/dist/plugin.wasm differ diff --git a/plugins/official/key-promoter/dist/plugin.wasm.sources b/plugins/official/key-promoter/dist/plugin.wasm.sources index 45055cf8cf..1d25a7bfb0 100644 --- a/plugins/official/key-promoter/dist/plugin.wasm.sources +++ b/plugins/official/key-promoter/dist/plugin.wasm.sources @@ -1 +1 @@ -c64b316772ea26ce5e2669025d55ba4af9b9a22f225971f361ee9716ae1cbbd4 +230826d223bcbdb64b053a74063e2ec735557a09bb88f2162a526f36a3042dcd diff --git a/plugins/official/license-header/dist/plugin.wasm b/plugins/official/license-header/dist/plugin.wasm index c7906b376c..0e10babfbc 100644 Binary files a/plugins/official/license-header/dist/plugin.wasm and b/plugins/official/license-header/dist/plugin.wasm differ diff --git a/plugins/official/license-header/dist/plugin.wasm.sources b/plugins/official/license-header/dist/plugin.wasm.sources index 023242b9d9..9769fb26a5 100644 --- a/plugins/official/license-header/dist/plugin.wasm.sources +++ b/plugins/official/license-header/dist/plugin.wasm.sources @@ -1 +1 @@ -1c40bd1a24c77eade5f617d99b8719e1961979c30a77c613e07d97c1abc5b03f +cceee2cc6cb8ebb083d3fb68b9715570523b28c5dea3946097a168ce3262a0a5 diff --git a/plugins/official/mybatis/dist/plugin.wasm b/plugins/official/mybatis/dist/plugin.wasm index 10246725f3..35ef67700c 100644 Binary files a/plugins/official/mybatis/dist/plugin.wasm and b/plugins/official/mybatis/dist/plugin.wasm differ diff --git a/plugins/official/mybatis/dist/plugin.wasm.sources b/plugins/official/mybatis/dist/plugin.wasm.sources index b0ffa6a814..0eda844c06 100644 --- a/plugins/official/mybatis/dist/plugin.wasm.sources +++ b/plugins/official/mybatis/dist/plugin.wasm.sources @@ -1 +1 @@ -9df4fce831ca53f8e26ae3148c2525c42f8d2473c88da344b0890c85dcac13d6 +5b9a6206e44fdec0d1351457cc0209110a20e5427014eb5be55f004dfb1f6de5 diff --git a/plugins/official/regex-tester/dist/plugin.wasm b/plugins/official/regex-tester/dist/plugin.wasm index 301868d7fd..68a7f919b5 100644 Binary files a/plugins/official/regex-tester/dist/plugin.wasm and b/plugins/official/regex-tester/dist/plugin.wasm differ diff --git a/plugins/official/regex-tester/dist/plugin.wasm.sources b/plugins/official/regex-tester/dist/plugin.wasm.sources index c6132e8413..afd29f43f7 100644 --- a/plugins/official/regex-tester/dist/plugin.wasm.sources +++ b/plugins/official/regex-tester/dist/plugin.wasm.sources @@ -1 +1 @@ -811e77cd9740eecd4007f1104343b6d0943920160a5ab7c41018c932ab5148f6 +f4ab582e8e134d33e0cdea1e18f2cad6d6e46c6bd736c58996c1a54b61f35e25 diff --git a/plugins/official/solidity/dist/plugin.wasm b/plugins/official/solidity/dist/plugin.wasm index 7fceec022e..a56db99233 100644 Binary files a/plugins/official/solidity/dist/plugin.wasm and b/plugins/official/solidity/dist/plugin.wasm differ diff --git a/plugins/official/solidity/dist/plugin.wasm.sources b/plugins/official/solidity/dist/plugin.wasm.sources index 1bb0af822d..7174e2b821 100644 --- a/plugins/official/solidity/dist/plugin.wasm.sources +++ b/plugins/official/solidity/dist/plugin.wasm.sources @@ -1 +1 @@ -cef63193655a8fe67397b6cc7c60a082cd0feddea6a7516d8a77c5feb15d5588 +c142297e91cdde9023185a2d6ccdafae7c49efc4f391145946dedea663d90c91 diff --git a/plugins/official/string-tools/dist/plugin.wasm b/plugins/official/string-tools/dist/plugin.wasm index 172db556b7..aed212a9f3 100644 Binary files a/plugins/official/string-tools/dist/plugin.wasm and b/plugins/official/string-tools/dist/plugin.wasm differ diff --git a/plugins/official/string-tools/dist/plugin.wasm.sources b/plugins/official/string-tools/dist/plugin.wasm.sources index ac61810282..a87507b265 100644 --- a/plugins/official/string-tools/dist/plugin.wasm.sources +++ b/plugins/official/string-tools/dist/plugin.wasm.sources @@ -1 +1 @@ -845c85070a383baa9b28c451175273db83a0f11c14a089cd4ec39eeb302f9e7c +25ed07e1ec5123e182a62aa6b1e8f0411a04e54caa95e6a02a5cb091811cc78f diff --git a/plugins/official/test-runner/dist/plugin.wasm b/plugins/official/test-runner/dist/plugin.wasm index 73599dec19..1b9913b60c 100644 Binary files a/plugins/official/test-runner/dist/plugin.wasm and b/plugins/official/test-runner/dist/plugin.wasm differ diff --git a/plugins/official/test-runner/dist/plugin.wasm.sources b/plugins/official/test-runner/dist/plugin.wasm.sources index e176486e4b..a8769ca986 100644 --- a/plugins/official/test-runner/dist/plugin.wasm.sources +++ b/plugins/official/test-runner/dist/plugin.wasm.sources @@ -1 +1 @@ -48f302f820ec837bace09a3299d8d3835314445c7da0c12f2f2c49559655832f +3384c291454845793f3848411f9f09e49f61b847a14ca6b99b255bb358003751 diff --git a/plugins/official/todo-finder/dist/plugin.wasm b/plugins/official/todo-finder/dist/plugin.wasm index b51b3b4c45..6d33759058 100644 Binary files a/plugins/official/todo-finder/dist/plugin.wasm and b/plugins/official/todo-finder/dist/plugin.wasm differ diff --git a/plugins/official/todo-finder/dist/plugin.wasm.sources b/plugins/official/todo-finder/dist/plugin.wasm.sources index 003bb4992d..ac963ae63d 100644 --- a/plugins/official/todo-finder/dist/plugin.wasm.sources +++ b/plugins/official/todo-finder/dist/plugin.wasm.sources @@ -1 +1 @@ -f59fcefbb81a5df556fb806ffc824460f24d0935c2a60e72889ed0124ae62a3c +8e4da9f7e3844588038af581825d28be1a8b797b0433905cfbe47ad973c99d10 diff --git a/sdk/rust/openidea-plugin/src/lib.rs b/sdk/rust/openidea-plugin/src/lib.rs index dcfaa11ca4..e13373773d 100644 --- a/sdk/rust/openidea-plugin/src/lib.rs +++ b/sdk/rust/openidea-plugin/src/lib.rs @@ -55,6 +55,7 @@ pub mod search; pub mod semantic_tokens; pub mod sse; pub mod syntax; +pub mod syntax_decorations; pub mod text; mod types; pub mod views; @@ -248,6 +249,17 @@ pub mod inlay_bindings { }); } +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +pub mod syntax_decoration_bindings { + wit_bindgen::generate!({ + world: "syntax-decorations", path: "wit", pub_export_macro: true, + export_macro_name: "__export_syntax_decorations_world", + default_bindings_module: "openidea_plugin::syntax_decoration_bindings", + with: { "openidea:plugin/types@1.20.0": crate::bindings::openidea::plugin::types }, + }); +} + #[cfg(target_arch = "wasm32")] #[doc(hidden)] pub mod file_actions_bindings { @@ -387,6 +399,9 @@ macro_rules! __optional_exports { (inlay_hints, $plugin:ty, $component:ident) => { $crate::__inlay_hints_exports!($plugin, $component); }; + (syntax_decorations, $plugin:ty, $component:ident) => { + $crate::__syntax_decorations_exports!($plugin, $component); + }; (syntax, $plugin:ty, $component:ident) => { impl $crate::syntax_bindings::exports::openidea::plugin::syntax_provider::Guest for $component { fn highlights( @@ -750,6 +765,30 @@ macro_rules! __inlay_hints_exports { }; } +/// `register_plugin!(T, syntax_decorations)`: `T` also exports +/// [`SyntaxDecorations`](crate::syntax_decorations::SyntaxDecorations). +#[cfg(target_arch = "wasm32")] +#[doc(hidden)] +#[macro_export] +macro_rules! __syntax_decorations_exports { + ($plugin:ty, $component:ident) => { + impl $crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider::Guest + for $component + { + fn syntax_decorations( + request: $crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider::DecorationRequest, + ) -> ::std::vec::Vec< + $crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider::SyntaxMark, + > { + $crate::__rt::syntax_decorations::<$plugin>(request) + } + } + $crate::syntax_decoration_bindings::__export_syntax_decorations_world!( + $component with_types_in $crate::syntax_decoration_bindings + ); + }; +} + #[doc(hidden)] #[macro_export] macro_rules! __plugin_exports { @@ -1044,6 +1083,38 @@ pub mod __rt { .map(|h| w::HoverContent { markdown: h.markdown, range: h.range.map(crate::host::__range_to) }) } + pub fn syntax_decorations<T: Plugin + crate::syntax_decorations::SyntaxDecorations + Default>( + request: crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider::DecorationRequest, + ) -> Vec<crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider::SyntaxMark> + { + use crate::syntax_decoration_bindings::exports::openidea::plugin::syntax_decorations_provider as w; + let request = crate::syntax_decorations::SyntaxDecorationRequest { + document: crate::syntax_decorations::SyntaxDocument { + path: request.document.path, + language: request.document.language, + version: request.document.version, + }, + ranges: request.ranges.into_iter().map(crate::host::__range_from).collect(), + nodes: request + .nodes + .into_iter() + .map(|n| crate::syntax_decorations::SyntaxNode { + name: n.name, + range: crate::host::__range_from(n.range), + parent: n.parent, + }) + .collect(), + }; + with::<T, _>(|p| p.syntax_decorations(&request)) + .into_iter() + .map(|m| w::SyntaxMark { + range: crate::host::__range_to(m.range), + token: m.token, + foreground: m.foreground.map(|f| w::SyntaxForeground { dark: f.dark, light: f.light }), + }) + .collect() + } + pub fn inlay_hints<T: Plugin + crate::inlay_hints::InlayHints + Default>( d: crate::inlay_bindings::exports::openidea::plugin::inlay_hints_provider::Document, range: b::types::Range, diff --git a/sdk/rust/openidea-plugin/src/syntax_decorations.rs b/sdk/rust/openidea-plugin/src/syntax_decorations.rs new file mode 100644 index 0000000000..7b6d6ca985 --- /dev/null +++ b/sdk/rust/openidea-plugin/src/syntax_decorations.rs @@ -0,0 +1,65 @@ +//! Theme-token foreground marks driven by a syntax snapshot the editor already has. +//! +//! Register with `register_plugin!(MyPlugin, syntax_decorations)` and declare +//! `kinds = ["syntax-decorations"]`. Node names belong to the editor's parser; +//! they are not a contract shared by every language. A mark is a theme token +//! (`rainbow-1` … `rainbow-5`) or its own colours for dark and light themes +//! ([`SyntaxMark::colored`]). Ranges are UTF-16, the same as the rest of the API. + +use crate::types::Range; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxDocument { + pub path: String, + pub language: String, + pub version: u64, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxNode { + pub name: String, + pub range: Range, + pub parent: Option<u32>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxDecorationRequest { + pub document: SyntaxDocument, + pub ranges: Vec<Range>, + pub nodes: Vec<SyntaxNode>, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxMark { + pub range: Range, + pub token: String, + pub foreground: Option<SyntaxForeground>, +} + +/// `#rrggbb` or `#rrggbbaa` colours for dark and for light themes. A mark with an +/// invalid colour is dropped by the host. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SyntaxForeground { + pub dark: String, + pub light: String, +} + +impl SyntaxMark { + /// A mark in a theme token, `rainbow-1` … `rainbow-5`. + pub fn new(range: Range, token: impl Into<String>) -> Self { + Self { range, token: token.into(), foreground: None } + } + + /// A mark in its own colours: `dark` on dark themes, `light` on light ones. + pub fn colored(range: Range, dark: impl Into<String>, light: impl Into<String>) -> Self { + Self { + range, + token: String::new(), + foreground: Some(SyntaxForeground { dark: dark.into(), light: light.into() }), + } + } +} + +pub trait SyntaxDecorations { + fn syntax_decorations(&mut self, request: &SyntaxDecorationRequest) -> Vec<SyntaxMark>; +} diff --git a/sdk/rust/openidea-plugin/wit/plugin.wit b/sdk/rust/openidea-plugin/wit/plugin.wit index af3b122631..e802e21e13 100644 --- a/sdk/rust/openidea-plugin/wit/plugin.wit +++ b/sdk/rust/openidea-plugin/wit/plugin.wit @@ -232,3 +232,8 @@ world run-configuration-completion-exports { export run-configuration-completion world plugin-search { include plugin; export search-provider; } /// Optional export composed with the base plugin by the SDK. world search { export search-provider; } + +/// A plugin that paints theme-token foreground marks from a syntax snapshot (API 1.20). +world plugin-syntax-decorations { include plugin; export syntax-decorations-provider; } +/// Export-only syntax decorations, composed with the base plugin world. +world syntax-decorations { export syntax-decorations-provider; } diff --git a/sdk/rust/openidea-plugin/wit/syntax-decorations.wit b/sdk/rust/openidea-plugin/wit/syntax-decorations.wit new file mode 100644 index 0000000000..3c5bdb4c32 --- /dev/null +++ b/sdk/rust/openidea-plugin/wit/syntax-decorations.wit @@ -0,0 +1,69 @@ +package openidea:plugin@1.20.0; + +/// Optional export (world `plugin-syntax-decorations`): foreground marks for +/// documents of the languages declared with the `syntax-decorations` provider +/// kind. The host sends the ranges it is painting and a bounded slice of the +/// editor's existing syntax tree. The plugin does not parse, and the host does +/// not run a second parser. +/// +/// Node `name`s come from that editor's parser. They are not a stable +/// vocabulary across languages or parser implementations. Ranges use the +/// shared UTF-16 `types.range` (0-based line, UTF-16 column). +/// +/// A mark paints its `foreground` colours when it has them, otherwise its +/// `token`: `rainbow-1` … `rainbow-5`, which the host maps onto the theme's +/// existing `--syn-rainbow-1` … `--syn-rainbow-5` colours. A mark with an +/// invalid colour or an unknown token is dropped. Only the foreground changes. +/// API 1.20. +interface syntax-decorations-provider { + use types.{range}; + + /// The open editor the host is asking about. `version` is the host + /// buffer version at the start of this call. + record document { + path: string, + language: string, + version: u64, + } + + /// One node of the editor's current syntax tree. `parent` is an index + /// into `decoration-request.nodes`. Index 0 is a real node. The index + /// may be greater than the child's, because the list is ordered by + /// position, not parent-before-child. `parent` is none when that + /// ancestor was not included: the tree may be partial, and the node + /// budget can drop an ancestor while keeping the child. None does not + /// mean the node is the root of the real tree. `name` belongs to the + /// editor's parser and is not stable across parsers. + record syntax-node { + name: string, + range: range, + parent: option<u32>, + } + + record decoration-request { + document: document, + /// Ranges the host wants marks for (visible ranges and sticky header + /// lines). At most 32. + ranges: list<range>, + /// At most 8192 nodes. + nodes: list<syntax-node>, + } + + /// Foreground colours of a mark: `#rrggbb`, or `#rrggbbaa` with an alpha + /// (`ff` fully opaque), one for dark themes and one for light themes. + record syntax-foreground { + dark: string, + light: string, + } + + /// A foreground mark. `token` is `rainbow-1` … `rainbow-5`, and may be + /// empty when `foreground` is set. + record syntax-mark { + range: range, + token: string, + foreground: option<syntax-foreground>, + } + + /// Marks for `request`, under the edit-path budget. At most 10,000 are kept. + syntax-decorations: func(request: decoration-request) -> list<syntax-mark>; +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 6a991324b1..b599190033 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -617,6 +617,8 @@ plugin_set_ui_locale always project_host bin plugin_stage_package always desktop bindings async plugin_status_items trusted project_host bindings sync plugin_subscribe always desktop bindings sync +plugin_syntax_decoration_languages trusted project_host bindings sync +plugin_syntax_decorations trusted project_host bindings async plugin_terminal_session_close trusted project_host bindings sync plugin_terminal_session_spawn trusted project_host bindings async plugin_uninstall outside_restricted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index cc1b473378..56eb1846b1 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1713,6 +1713,13 @@ export const commands = { pluginStatusItems: () => __TAURI_INVOKE<PluginStatusItem_Serialize[]>("plugin_status_items"), /** Routes this window's plugin events to `on_event` (replaces an earlier subscription). */ pluginSubscribe: (onEvent: Channel<PluginEvent_Deserialize>) => __TAURI_INVOKE<void>("plugin_subscribe", { onEvent }), + /** Languages that have a syntax-decoration provider. Does not load plugin code. */ + pluginSyntaxDecorationLanguages: () => __TAURI_INVOKE<string[]>("plugin_syntax_decoration_languages"), + /** + * Foreground marks for one open document. An unknown document, a document the + * window does not have, or an invalid snapshot answers with no marks. + */ + pluginSyntaxDecorations: (request: RequestId, doc: DocId, ranges: Range[], nodes: SyntaxNodeSnapshot[], epoch: number) => typedError<SyntaxDecorationBatch, IdeError>(__TAURI_INVOKE("plugin_syntax_decorations", { request, doc, ranges, nodes, epoch })), /** Marks a keyed tab closed before ending its process. */ pluginTerminalSessionClose: (operation: string) => typedError<null, IdeError>(__TAURI_INVOKE("plugin_terminal_session_close", { operation })), /** Starts only the pinned command recorded for this window's terminal operation. */ @@ -17363,6 +17370,26 @@ export type SyntaxCacheStats = { fullParses: number, }; +/** A theme-token mark returned by one plugin. `plugin` is assigned by the host. */ +export type SyntaxDecoration = { + plugin: string, + range: Range, + token: string, + /** Checked colours, `#rrggbb` / `#rrggbbaa` in lower case; painted instead of `token`. */ + foreground: SyntaxForeground | null, +}; + +/** + * Answer of `plugin_syntax_decorations`. `stale` means the document changed + * while the plugins were running; `marks` is then empty. + */ +export type SyntaxDecorationBatch = { + version: number, + epoch: number, + stale: boolean, + marks: SyntaxDecoration[], +}; + export type SyntaxError = { kind: SyntaxErrorKind, range: Range, @@ -17385,6 +17412,12 @@ export type SyntaxErrors = { truncated: boolean, }; +/** A mark's own foreground for dark and for light themes. */ +export type SyntaxForeground = { + dark: string, + light: string, +}; + /** Highlight classes sent to the UI, which maps each onto a Lezer tag. */ export type SyntaxHighlightKind = "keyword" | "string" | "stringSpecial" | "escape" | "regexp" | "atom" | "number" | "constant" | "comment" | "docComment" | "function" | "functionCall" | "builtin" | "type" | "namespace" | "variable" | "selfVariable" | "property" | "attribute" | "macro" | "label" | "tag" | "operator" | "punctuation" | "parameter" | /** A shell command name (`pgrep`, a script's own function). */ @@ -17415,6 +17448,16 @@ export type SyntaxNode = { hasError: boolean, }; +/** + * One node of an editor syntax snapshot (`syntax-decorations-provider`). + * `parent` indexes this same list. + */ +export type SyntaxNodeSnapshot = { + name: string, + range: Range, + parent: number | null, +}; + /** A sortable table's order: the column and the direction. */ export type TableSort = { column: number, diff --git a/src/editor/core/cm/renderLineContent.ts b/src/editor/core/cm/renderLineContent.ts index 9a9890136c..aa7edae405 100644 --- a/src/editor/core/cm/renderLineContent.ts +++ b/src/editor/core/cm/renderLineContent.ts @@ -20,6 +20,8 @@ export interface ClassMark { from: number; to: number; cls: string; + /** Present only when the decoration already carried a host-checked style. */ + style?: string; } /** The decoration sets of the {@link previewHighlights} sources (compare them to see a change). */ @@ -33,7 +35,8 @@ export function previewMarks(state: EditorState, from: number, to: number): Clas for (const set of previewHighlightSets(state)) set.between(from, to, (f, t, deco) => { const cls = deco.spec.class as string | undefined; - if (cls && t > from && f < to) out.push({ from: Math.max(f, from), to: Math.min(t, to), cls }); + const style = (deco.spec.attributes as { style?: string } | undefined)?.style; + if (cls && t > from && f < to) out.push({ from: Math.max(f, from), to: Math.min(t, to), cls, style }); }); return out; } @@ -76,16 +79,17 @@ export function renderSyntaxRange( ) { let pos = start; let next = 0; - const span = (cls: string, child: Node) => { + const span = (cls: string, child: Node, style?: string) => { const el = document.createElement("span"); el.className = cls; + if (style) el.setAttribute("style", style); el.appendChild(child); return el; }; // The text up to `to`, in the syntax class with the marks covering it inside, as the editor nests them. const node = (to: number, cls: string): Node => { let out: Node = document.createTextNode(doc.sliceString(pos, to)); - for (const m of marks) if (m.from <= pos && m.to >= to) out = span(m.cls, out); + for (const m of marks) if (m.from <= pos && m.to >= to) out = span(m.cls, out, m.style); pos = to; return cls ? span(cls, out) : out; }; diff --git a/src/features/plugins/__tests__/syntaxDecorations.test.ts b/src/features/plugins/__tests__/syntaxDecorations.test.ts new file mode 100644 index 0000000000..1f19830dcf --- /dev/null +++ b/src/features/plugins/__tests__/syntaxDecorations.test.ts @@ -0,0 +1,553 @@ +import { readFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { javascript } from "@codemirror/lang-javascript"; +import { syntaxHighlighting } from "@codemirror/language"; +import { Prec, EditorState } from "@codemirror/state"; +import { EditorView, Decoration } from "@codemirror/view"; +import { _addEditor, _removeEditor, documentSynced, type TextEditorHandle } from "@/editor/api"; +import { openideaHighlightStyle } from "@/editor/core/cm/highlight"; +import { renderLineContent, previewHighlights } from "@/editor/core/cm/renderLineContent"; +import { lspDoc } from "@/editor/lsp/lsp"; +import { completedSyntaxState } from "@/test/syntax"; +import { + SYNTAX_TOKEN_CLASS, + syntaxDecorationExtensions, + syntaxDecorationSet, + syntaxDecorationSpans, + syntaxDecorationsRefresh, + PLUGIN_FOREGROUND_CLASS, + foregroundStyle, + syntaxTokenTheme, + syntaxDecorationPluginsChanged, + type SyntaxDecorationQuery, + type SyntaxDecorationBatch, + type SyntaxDecorationMark, +} from "../syntaxDecorations"; +import { syntaxSnapshot } from "../syntaxSnapshot"; +import { usePlugins } from "../store"; + +const ctx = { doc: 1, path: "/p/a.js", language: "javascript", uiMode: null, readOnly: false }; +const views: EditorView[] = []; + +afterEach(() => { + vi.useRealTimers(); + for (const view of views) view.destroy(); + views.length = 0; + document.body.replaceChildren(); +}); + +function parsed(doc: string) { + return completedSyntaxState(EditorState.create({ doc, extensions: [javascript()] })); +} + +function mark(token: string, from = 0, to = 5, plugin = "test.syntax"): SyntaxDecorationMark { + return { plugin, token, foreground: null, range: { start: { line: 0, col: from }, end: { line: 0, col: to } } }; +} + +function colored(dark: string, light: string, from = 0, to = 5): SyntaxDecorationMark { + return { ...mark("", from, to), foreground: { dark, light } }; +} + +describe("syntax snapshot", () => { + it("includes ancestors that start before the requested range", () => { + const doc = "function hello() {\n return 1;\n}\n"; + const state = parsed(doc); + const line = state.doc.line(2); + const nodes = syntaxSnapshot(state, [{ from: line.from, to: line.to }]); + expect(nodes.some((node) => node.range.start.line === 0)).toBe(true); + expect(nodes.some((node) => node.parent === 0)).toBe(true); + const inner = nodes.find((node) => node.range.start.line === 1); + expect(inner?.parent).not.toBeNull(); + const parent = nodes[inner!.parent!]; + expect(parent).toBeTruthy(); + expect(parent!.range.start.line).toBeLessThanOrEqual(inner!.range.start.line); + }); + + it("covers every requested range and keeps parent indexes inside the list", () => { + const doc = "const a = 1;\nconst b = 2;\n"; + const state = parsed(doc); + const first = state.doc.line(1); + const second = state.doc.line(2); + const nodes = syntaxSnapshot(state, [ + { from: first.from, to: first.to }, + { from: second.from, to: second.to }, + ]); + expect(nodes.some((node) => node.name.length > 0 && node.range.start.line === 0)).toBe(true); + expect(nodes.some((node) => node.range.start.line === 1 || node.range.end.line >= 1)).toBe(true); + for (const node of nodes) if (node.parent != null) expect(nodes[node.parent]).toBeTruthy(); + const variables = nodes.filter((node) => node.name === "VariableDefinition"); + expect(variables).toHaveLength(2); + expect(variables.map(({ parent }) => nodes[parent!]?.name)).toEqual(["VariableDeclaration", "VariableDeclaration"]); + expect(nodes.filter((node) => node.name === "Script")).toHaveLength(1); + }); + + it("counts UTF-16 columns", () => { + const doc = "a😀b"; + const state = parsed(doc); + const nodes = syntaxSnapshot(state, [{ from: 0, to: doc.length }]); + expect(nodes.some((node) => node.range.end.col === 4)).toBe(true); + }); + + it("returns nothing for an empty document or an empty range", () => { + const empty = EditorState.create({ doc: "" }); + expect(syntaxSnapshot(empty, [{ from: 0, to: 0 }])).toEqual([]); + const state = parsed("const a = 1;\n"); + expect(syntaxSnapshot(state, [{ from: 2, to: 2 }])).toEqual([]); + }); + + it("does not invent nodes where the editor has no syntax tree", () => { + const state = EditorState.create({ doc: "function a() { return 1 }" }); + expect(syntaxSnapshot(state, [{ from: 0, to: 8 }])).toEqual([]); + }); + + it("stops at the node limit and stays inside the requested window", () => { + const doc = "let a = 1;\n".repeat(400); + const state = parsed(doc); + const limited = syntaxSnapshot(state, [{ from: 0, to: 10 }], 3); + expect(limited.length).toBeLessThanOrEqual(3); + for (const [index, node] of limited.entries()) { + expect(node.parent === null || (node.parent !== index && node.parent >= 0 && node.parent < limited.length)).toBe( + true, + ); + const seen = new Set<number>([index]); + let parent = node.parent; + while (parent != null) { + expect(seen.has(parent)).toBe(false); + seen.add(parent); + parent = limited[parent]!.parent; + } + } + const window = syntaxSnapshot(state, [{ from: 0, to: 10 }]); + expect(window.length).toBeGreaterThan(0); + expect(window.every((node) => node.range.start.line === 0)).toBe(true); + }); + + it("adds sticky header lines that sit outside the visible range", () => { + const doc = "function hello() {\n return 1;\n}\n"; + const state = parsed(doc); + const inner = state.doc.line(2); + const spans = syntaxDecorationSpans(state, [{ from: inner.from, to: inner.to }]); + expect(spans.some((span) => span.from === 0)).toBe(true); + expect(spans.some((span) => span.from === inner.from)).toBe(true); + }); + + it("keeps visible ranges and drops sticky headers once 32 ranges are full", () => { + const doc = `function hello() {\n${"x ".repeat(40)}\n}\n`; + const state = parsed(doc); + const line = state.doc.line(2); + const visible = Array.from({ length: 32 }, (_, i) => ({ from: line.from + i * 2, to: line.from + i * 2 + 1 })); + const spans = syntaxDecorationSpans(state, visible); + expect(spans).toHaveLength(32); + expect(spans.some((span) => span.from === 0)).toBe(false); + expect(spans.every((span) => span.from >= line.from)).toBe(true); + }); +}); + +describe("syntax decorations", () => { + it("paints an allowlisted token inside the syntax span and ignores the rest", () => { + const doc = EditorState.create({ doc: "const value = 1;\n", extensions: [javascript()] }).doc; + const set = syntaxDecorationSet(doc, [ + mark("rainbow-3"), + mark("red; color: expression(1)"), + mark("rainbow-1", 0, 0), + { ...mark("rainbow-1"), plugin: "" }, + { ...mark("rainbow-1", 6, 11), plugin: "other.plugin" }, + ]); + let painted: string[] = []; + set.between(0, doc.length, (_from, _to, deco) => { + painted.push(deco.spec.class as string); + }); + expect(painted).toEqual([SYNTAX_TOKEN_CLASS["rainbow-3"], SYNTAX_TOKEN_CLASS["rainbow-1"]]); + }); + + it("paints a mark's own colours and rejects anything else", () => { + const doc = EditorState.create({ doc: "const value = 1;\n" }).doc; + const set = syntaxDecorationSet(doc, [ + colored("#80cbc4", "#23766f"), + colored("#80cbc4;color:red", "#23766f"), + colored("80cbc4", "#23766f"), + colored("var(--syn-rainbow-1)", "#23766f"), + mark("cm-plugin-fg"), + ]); + const painted: { className: string; style: string }[] = []; + set.between(0, doc.length, (_from, _to, deco) => { + painted.push({ className: deco.spec.class as string, style: (deco.spec.attributes?.style as string) ?? "" }); + }); + expect(painted).toEqual([ + { className: PLUGIN_FOREGROUND_CLASS, style: "--plugin-fg-dark:#80cbc4;--plugin-fg-light:#23766f" }, + ]); + expect(foregroundStyle({ dark: "#80cbc4cc", light: "#23766f" })).toBe( + "--plugin-fg-dark:#80cbc4cc;--plugin-fg-light:#23766f", + ); + expect(foregroundStyle(null)).toBeNull(); + }); + + it("keeps both theme colours on the sticky line without changing typography", () => { + const doc = "function hello() {\n return 1;\n}\n"; + const set = syntaxDecorationSet(EditorState.create({ doc }).doc, [colored("#f0a6ca", "#a13c76", 0, 8)]); + const state = completedSyntaxState( + EditorState.create({ + doc, + extensions: [javascript(), syntaxHighlighting(openideaHighlightStyle), previewHighlights.of(() => set)], + }), + ); + const target = document.createElement("div"); + renderLineContent(state, 1, target); + const painted = target.querySelector(`.${PLUGIN_FOREGROUND_CLASS}`); + expect(painted?.textContent).toBe("function"); + expect(painted?.getAttribute("style")).toBe("--plugin-fg-dark:#f0a6ca;--plugin-fg-light:#a13c76"); + expect(painted?.getAttribute("style") ?? "").not.toMatch(/font-weight|font-style|text-decoration/i); + }); + + it("uses only the existing rainbow variables and does not change typography", () => { + const theme = syntaxTokenTheme(); + expect(Object.keys(theme)).toHaveLength(5); + for (const [selector, style] of Object.entries(theme)) { + expect(selector).toMatch(/^\.cm-plugin-token-rainbow-[1-5]$/); + expect(style).toEqual({ color: `var(--syn-${selector.slice(".cm-plugin-token-".length)})` }); + expect(style).not.toHaveProperty("fontWeight"); + expect(style).not.toHaveProperty("fontStyle"); + } + }); + + it("nests the token inside the sticky line's syntax span", () => { + const doc = "function hello() {\n return 1;\n}\n"; + const set = syntaxDecorationSet(EditorState.create({ doc }).doc, [mark("rainbow-2", 0, 8)]); + const state = completedSyntaxState( + EditorState.create({ + doc, + extensions: [javascript(), syntaxHighlighting(openideaHighlightStyle), previewHighlights.of(() => set)], + }), + ); + const target = document.createElement("div"); + renderLineContent(state, 1, target); + const painted = target.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-2"]}`); + expect(painted?.textContent).toBe("function"); + expect(painted?.parentElement).not.toBe(target); + expect(painted?.getAttribute("style") ?? "").not.toMatch(/font-weight|font-style/i); + }); + + it("nests a later plugin inside an earlier one on the same range", () => { + const doc = EditorState.create({ doc: "const value = 1;\n" }).doc; + const set = syntaxDecorationSet(doc, [mark("rainbow-1", 0, 5, "a.plugin"), mark("rainbow-2", 0, 5, "b.plugin")]); + const view = new EditorView({ + parent: document.body, + doc, + extensions: [Prec.highest(EditorView.decorations.of(set))], + }); + views.push(view); + const line = view.dom.querySelector(".cm-line"); + expect( + line?.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-2"]} .${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)?.textContent, + ).toBe("const"); + }); + + it("refreshes on edits, skips selection changes, rejects a stale answer and clears when disabled", async () => { + vi.useFakeTimers(); + let enabled = true; + let calls = 0; + let staleOnce = true; + const view = new EditorView({ + parent: document.body, + doc: "const value = 1;\n", + extensions: [ + javascript(), + syntaxHighlighting(openideaHighlightStyle), + lspDoc.of(ctx), + syntaxDecorationExtensions({ + active: () => enabled, + query: async (_doc, query) => { + calls += 1; + const stale = staleOnce; + staleOnce = false; + const batch: SyntaxDecorationBatch = { + version: 4, + epoch: query.epoch, + stale, + marks: stale ? [] : [mark("rainbow-1", 6, 11)], + }; + return batch; + }, + }), + ], + }); + views.push(view); + await vi.advanceTimersByTimeAsync(200); + expect(calls).toBeGreaterThanOrEqual(2); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)?.textContent).toBe("value"); + const token = view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)!; + expect(token.parentElement).not.toBe(token.closest(".cm-line")); + const afterPaint = calls; + view.dispatch({ selection: { anchor: 3 } }); + await vi.advanceTimersByTimeAsync(80); + expect(calls).toBe(afterPaint); + view.dispatch({ changes: { from: 0, to: 0, insert: " " } }); + await vi.advanceTimersByTimeAsync(80); + expect(calls).toBeGreaterThan(afterPaint); + enabled = false; + view.dispatch({ effects: syntaxDecorationsRefresh.of(null) }); + await vi.advanceTimersByTimeAsync(80); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)).toBeNull(); + }); + + it("does not ask about a document the code insight limit already rejected", async () => { + vi.useFakeTimers(); + let calls = 0; + const view = new EditorView({ + parent: document.body, + doc: "const value = 1;\n", + extensions: [ + lspDoc.of({ ...ctx, large: true }), + syntaxDecorationExtensions({ + query: async () => { + calls += 1; + return { version: 1, epoch: 1, stale: false, marks: [mark("rainbow-1")] }; + }, + }), + ], + }); + views.push(view); + await vi.advanceTimersByTimeAsync(80); + expect(calls).toBe(0); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)).toBeNull(); + }); + + it("asks about a document inside the code insight limit", async () => { + vi.useFakeTimers(); + let calls = 0; + const view = new EditorView({ + parent: document.body, + doc: "const value = 1;\n", + extensions: [ + javascript(), + lspDoc.of(ctx), + syntaxDecorationExtensions({ + active: () => true, + query: async (_doc, query) => { + calls += 1; + return { version: 1, epoch: query.epoch, stale: false, marks: [mark("rainbow-1")] }; + }, + }), + ], + }); + views.push(view); + await vi.advanceTimersByTimeAsync(80); + expect(calls).toBeGreaterThan(0); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)?.textContent).toBe("const"); + }); + + it("has no fixed eight-million-character ceiling beside the code insight flag", () => { + const editor = readFileSync("src/features/plugins/syntaxDecorations.ts", "utf8"); + const host = readFileSync("crates/ide-host/src/plugins/commands.rs", "utf8"); + expect(editor).not.toContain("8_000_000"); + expect(editor).not.toContain("HEAVY_LIMIT"); + expect(host).not.toContain("8_000_000"); + }); + + it("orders a partial overlap by position, with the token inside a styled mark", () => { + const doc = EditorState.create({ doc: "const value = 1;\n" }).doc; + const token = syntaxDecorationSet(doc, [mark("rainbow-1", 0, 8, "a.plugin"), mark("rainbow-2", 4, 11, "b.plugin")]); + const styled = Decoration.set([ + Decoration.mark({ attributes: { style: "color: red; font-weight: 700" } }).range(0, 11), + ]); + const view = new EditorView({ + parent: document.body, + doc, + extensions: [EditorView.decorations.of(styled), Prec.highest(EditorView.decorations.of(token))], + }); + views.push(view); + const line = view.dom.querySelector(".cm-line"); + const early = line?.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`); + const late = line?.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-2"]}`); + expect(early).not.toBeNull(); + expect(late).not.toBeNull(); + const ownText = (el: Element | null | undefined) => + [...(el?.childNodes ?? [])] + .flatMap((node) => (node.nodeType === Node.TEXT_NODE ? [node.textContent] : [])) + .join(""); + expect(ownText(early)).toBe("cons"); + expect(ownText(late)).toBe("lue"); + expect(line?.textContent).toContain("const value"); + expect(line?.querySelector("[style*='font-weight']")).not.toBeNull(); + expect(early?.getAttribute("style") ?? "").not.toMatch(/font-weight/i); + expect(late?.getAttribute("style") ?? "").not.toMatch(/font-weight/i); + const overlap = line?.querySelector( + `.${SYNTAX_TOKEN_CLASS["rainbow-1"]} .${SYNTAX_TOKEN_CLASS["rainbow-2"]}, .${SYNTAX_TOKEN_CLASS["rainbow-2"]} .${SYNTAX_TOKEN_CLASS["rainbow-1"]}`, + ); + expect(overlap?.textContent).toBe("t va"); + }); +}); + +describe("syntax decoration lifecycle", () => { + function deferred() { + let resolve!: (batch: SyntaxDecorationBatch) => void; + let reject!: (error: unknown) => void; + const promise = new Promise<SyntaxDecorationBatch>((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; + } + + function editor( + query: (doc: number, query: SyntaxDecorationQuery, signal: AbortSignal) => Promise<SyntaxDecorationBatch>, + synced: () => Promise<void> = () => Promise.resolve(), + ) { + const view = new EditorView({ + parent: document.body, + doc: "const value = 1;\n", + extensions: [ + javascript(), + lspDoc.of(ctx), + documentSynced.of(synced), + syntaxDecorationExtensions({ active: () => true, query }), + ], + }); + views.push(view); + return view; + } + + it("drops a debounce that has not started when the editor is destroyed", async () => { + vi.useFakeTimers(); + let calls = 0; + const view = editor(async () => { + calls += 1; + return { version: 1, epoch: 1, stale: false, marks: [] }; + }); + expect(calls).toBe(0); + views.splice(views.indexOf(view), 1); + view.destroy(); + await vi.advanceTimersByTimeAsync(200); + expect(calls).toBe(0); + }); + + it("ignores a successful provider answer that arrives after destroy", async () => { + vi.useFakeTimers(); + let answer = deferred(); + let epoch = 0; + let signal: AbortSignal | undefined; + const view = editor((_doc, query, requestSignal) => { + epoch = query.epoch; + signal = requestSignal; + answer = deferred(); + return answer.promise; + }); + await vi.advanceTimersByTimeAsync(50); + const pending = answer; + views.splice(views.indexOf(view), 1); + view.destroy(); + expect(signal?.aborted).toBe(true); + pending.resolve({ version: 1, epoch, stale: false, marks: [mark("rainbow-1")] }); + await pending.promise; + }); + + it("coalesces typing, waits for synced edits and cancels superseded requests", async () => { + vi.useFakeTimers(); + let sync!: () => void; + const synced = new Promise<void>((resolve) => { + sync = resolve; + }); + const signals: AbortSignal[] = []; + const pending = deferred(); + const view = editor( + (_doc, _query, signal) => { + signals.push(signal); + return pending.promise; + }, + () => synced, + ); + const edit = () => view.dispatch({ changes: { from: 0, insert: " " } }); + for (let i = 0; i < 5; i++) { + edit(); + await vi.advanceTimersByTimeAsync(25); + } + await vi.advanceTimersByTimeAsync(50); + expect(signals).toHaveLength(0); + sync(); + await vi.advanceTimersByTimeAsync(0); + expect(signals).toHaveLength(1); + edit(); + expect(signals[0]?.aborted).toBe(true); + await vi.advanceTimersByTimeAsync(50); + expect(signals).toHaveLength(2); + }); + + it("ignores a rejected provider answer that arrives after destroy", async () => { + vi.useFakeTimers(); + let answer = deferred(); + const view = editor(() => { + answer = deferred(); + return answer.promise; + }); + await vi.advanceTimersByTimeAsync(50); + const pending = answer; + views.splice(views.indexOf(view), 1); + view.destroy(); + pending.reject(new Error("provider failed")); + await expect(pending.promise).rejects.toThrow("provider failed"); + }); +}); + +describe("syntax decoration plugin set", () => { + const handles: TextEditorHandle[] = []; + + afterEach(() => { + for (const handle of handles) _removeEditor(handle); + handles.length = 0; + usePlugins.setState({ plugins: [], ui: [], loaded: false }); + }); + + async function paint(change: () => void) { + vi.useFakeTimers(); + const pending: Array<(marks: SyntaxDecorationMark[]) => void> = []; + const view = new EditorView({ + parent: document.body, + doc: "const value = 1;\n", + extensions: [ + javascript(), + lspDoc.of(ctx), + syntaxDecorationExtensions({ + active: () => true, + query: (_doc, query) => + new Promise((resolve) => { + pending.push((marks) => resolve({ version: 1, epoch: query.epoch, stale: false, marks })); + }), + }), + ], + }); + views.push(view); + const handle: TextEditorHandle = { view, ctx }; + handles.push(handle); + _addEditor(handle); + await vi.advanceTimersByTimeAsync(50); + expect(pending.length).toBeGreaterThan(0); + const stale = pending.splice(0, pending.length); + change(); + for (const resolve of stale) resolve([mark("rainbow-1", 0, 5, "a.plugin"), mark("rainbow-2", 0, 5, "b.plugin")]); + await vi.advanceTimersByTimeAsync(80); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)).toBeNull(); + expect(pending.length).toBeGreaterThan(0); + pending[pending.length - 1]!([mark("rainbow-2", 0, 5, "b.plugin")]); + await vi.advanceTimersByTimeAsync(0); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-1"]}`)).toBeNull(); + expect(view.dom.querySelector(`.${SYNTAX_TOKEN_CLASS["rainbow-2"]}`)?.textContent).toBe("const"); + } + + it("does not apply an in-flight answer after a plugin is disabled", async () => { + await paint(() => { + usePlugins.setState({ plugins: [], ui: [] }); + syntaxDecorationPluginsChanged(); + }); + }); + + it("does not apply an in-flight answer after a plugin is uninstalled", async () => { + await paint(() => { + usePlugins.setState({ plugins: [], ui: [], loaded: true }); + syntaxDecorationPluginsChanged(); + }); + }); + + it("keeps another plugin's new answer after one provider is disabled", async () => { + await paint(() => syntaxDecorationPluginsChanged()); + }); +}); diff --git a/src/features/plugins/index.ts b/src/features/plugins/index.ts index 4db172d85c..00d9b56eee 100644 --- a/src/features/plugins/index.ts +++ b/src/features/plugins/index.ts @@ -14,6 +14,8 @@ import { pluginLanguageVisuals } from "./languageVisuals"; * * Editor contribution `plugins.lineMarkers`: gutter icons from plugin * `line-markers` providers (`lineMarkerGutter.ts`). + * Editor contribution `plugins.syntaxDecorations`: theme-token foreground marks + * from `syntax-decorations` providers (`syntaxDecorations.ts`). */ import { registerEditorContribution } from "@/editor/api"; import { executeAction, registerActions } from "@/platform/actions"; @@ -27,6 +29,7 @@ import { syncPluginExecutors } from "./executors"; import { showInstalledIntellijThemes } from "./intellijThemesDialogStore"; import { startWorkspaceContains } from "./workspaceContains"; import { startPluginDecorations } from "./decorations"; +import { startPluginSyntaxDecorations } from "./syntaxDecorations"; import { startPluginConsoleRules } from "./consoleRules"; import { startOneDarkNotice } from "./oneDarkNotice"; import { startIndexedMarkers } from "./indexedMarkers"; @@ -136,6 +139,7 @@ export function activate(): () => void { startOneDarkNotice(), startIndexedMarkers(), startPluginDecorations(), + startPluginSyntaxDecorations(), startPluginConsoleRules(), // Plugin custom editors (tab kind) and context menu entries. startViewUi((input) => void editorService().openInput(input)), diff --git a/src/features/plugins/syntaxDecorations.ts b/src/features/plugins/syntaxDecorations.ts new file mode 100644 index 0000000000..ab0c83f32b --- /dev/null +++ b/src/features/plugins/syntaxDecorations.ts @@ -0,0 +1,336 @@ +/** + * Theme-token foreground marks from plugins that implement + * `syntax-decorations`. The editor builds one syntax snapshot per refresh and + * the host asks every matching plugin. Rainbow tokens use the theme's + * `--syn-rainbow-*` variables. A mark's own `foreground` carries a dark and a + * light colour, and the host stylesheet switches between them, so a theme + * change does not ask the plugin again. + */ +import { syntaxTree } from "@codemirror/language"; +import { + Prec, + StateEffect, + StateField, + type EditorState, + type Extension, + type Range as CmRange, +} from "@codemirror/state"; +import { Decoration, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view"; +import { registerEditorContribution, shownAgain, useEditorRegistry, whenSynced } from "@/editor/api"; +import { enclosingHeaders } from "@/editor/core/cm/stickyScroll"; +import { MAX_PREVIEW_LINE_LENGTH, previewHighlights } from "@/editor/core/cm/renderLineContent"; +import { docOf, debounce } from "@/editor/lsp/lsp"; +import { offsetsToRange, rangeToOffsets } from "@/editor/lsp/positions"; +import { call, commands, isTauri, nextRequestId, onIdeEvent } from "@/platform/ipc"; +import { hasInvokeRoute } from "@/platform/tauriCore"; +import type { Range, SyntaxDecoration, SyntaxDecorationBatch, SyntaxNodeSnapshot } from "@/bindings"; +import { usePlugins } from "./store"; +import { MAX_SYNTAX_RANGES, syntaxSnapshot, type SyntaxSpan } from "./syntaxSnapshot"; + +export type SyntaxDecorationMark = SyntaxDecoration; +export type { SyntaxDecorationBatch, SyntaxNodeSnapshot }; + +/** Tokens the host accepts, mapped onto the existing rainbow palette. */ +export const SYNTAX_TOKEN_CLASS: Record<string, string> = { + "rainbow-1": "cm-plugin-token-rainbow-1", + "rainbow-2": "cm-plugin-token-rainbow-2", + "rainbow-3": "cm-plugin-token-rainbow-3", + "rainbow-4": "cm-plugin-token-rainbow-4", + "rainbow-5": "cm-plugin-token-rainbow-5", +}; + +/** Host-owned class. A plugin cannot choose this name or any other class. */ +export const PLUGIN_FOREGROUND_CLASS = "cm-plugin-fg"; + +const COLOR = /^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/; + +/** Colour variables for a mark's own foreground; `null` without one or with anything but checked colours. */ +export function foregroundStyle(foreground: SyntaxDecoration["foreground"]): string | null { + if (!foreground || !COLOR.test(foreground.dark) || !COLOR.test(foreground.light)) return null; + return `--plugin-fg-dark:${foreground.dark};--plugin-fg-light:${foreground.light}`; +} + +export function syntaxTokenTheme(): Record<string, { color: string }> { + const spec: Record<string, { color: string }> = {}; + for (const [token, cls] of Object.entries(SYNTAX_TOKEN_CLASS)) spec[`.${cls}`] = { color: `var(--syn-${token})` }; + return spec; +} + +export interface SyntaxDecorationQuery { + ranges: Range[]; + nodes: SyntaxNodeSnapshot[]; + epoch: number; +} + +const setMarks = StateEffect.define<DecorationSet>(); +export const syntaxDecorationsRefresh = StateEffect.define<null>(); + +const marksField = StateField.define<DecorationSet>({ + create: () => Decoration.none, + update(value, tr) { + for (const effect of tr.effects) if (effect.is(setMarks)) return effect.value; + return value.map(tr.changes); + }, +}); + +/** Drop tokens, ranges and plugin ids the host must not have produced. */ +export function syntaxDecorationSet(doc: EditorState["doc"], marks: readonly SyntaxDecorationMark[]): DecorationSet { + const built: CmRange<Decoration>[] = []; + const seen = new Set<string>(); + for (const mark of marks) { + const foreground = mark.foreground ? foregroundStyle(mark.foreground) : null; + const cls = mark.foreground + ? undefined + : Object.hasOwn(SYNTAX_TOKEN_CLASS, mark.token) + ? SYNTAX_TOKEN_CLASS[mark.token] + : undefined; + if ((!cls && !foreground) || mark.plugin.length === 0 || mark.plugin.length > 200) continue; + let from: number; + let to: number; + try { + ({ from, to } = rangeToOffsets(doc, mark.range)); + } catch { + continue; + } + if (from >= to || to > doc.length) continue; + const key = `${mark.plugin}\0${from}\0${to}\0${foreground ?? mark.token}`; + if (seen.has(key)) continue; + seen.add(key); + if (foreground) { + built.push( + Decoration.mark({ class: PLUGIN_FOREGROUND_CLASS, attributes: { style: foreground } }).range(from, to), + ); + } else if (cls) { + built.push(Decoration.mark({ class: cls }).range(from, to)); + } + } + built.sort((a, b) => a.from - b.from || a.to - b.to); + try { + return Decoration.set(built, true); + } catch { + return Decoration.none; + } +} + +/** Visible ranges plus the sticky header lines, which can sit outside the viewport. */ +export function syntaxDecorationSpans(state: EditorState, visible: readonly SyntaxSpan[]): SyntaxSpan[] { + const spans: SyntaxSpan[] = []; + const add = (from: number, to: number) => { + if (from >= to || spans.length >= MAX_SYNTAX_RANGES) return; + const hit = spans.find((span) => from <= span.to && to >= span.from); + if (!hit) spans.push({ from, to }); + else { + hit.from = Math.min(hit.from, from); + hit.to = Math.max(hit.to, to); + } + }; + for (const span of visible) add(Math.max(0, span.from), Math.min(state.doc.length, span.to)); + if (visible.length) { + const first = state.doc.lineAt(Math.max(0, Math.min(visible[0]!.from, state.doc.length))).number; + for (const lineNo of enclosingHeaders(state, first)) { + const line = state.doc.line(lineNo); + add(line.from, Math.min(line.to, line.from + MAX_PREVIEW_LINE_LENGTH)); + } + } + return spans; +} + +let languages: ReadonlySet<string> | null = null; +/** Bumped when the plugin set changes, before the language list is reloaded. */ +let pluginEpoch = 0; + +/** Drops in-flight answers. The language list is empty until the reload finishes. */ +export function syntaxDecorationPluginsChanged(): void { + languages = null; + pluginEpoch += 1; + poke(true); +} + +function languageActive(language: string): boolean { + return languages != null && (languages.has("*") || languages.has(language)); +} + +async function hostLanguages(): Promise<ReadonlySet<string>> { + if (!isTauri() && !hasInvokeRoute()) return new Set(); + try { + return new Set(await commands.pluginSyntaxDecorationLanguages()); + } catch { + return new Set(); + } +} + +async function hostDecorations( + doc: number, + query: SyntaxDecorationQuery, + signal: AbortSignal, +): Promise<SyntaxDecorationBatch> { + const request = nextRequestId(); + const abort = () => void commands.cancelRequest(request).catch(() => {}); + signal.addEventListener("abort", abort, { once: true }); + try { + return await call(commands.pluginSyntaxDecorations(request, doc, query.ranges, query.nodes, query.epoch)); + } finally { + signal.removeEventListener("abort", abort); + } +} + +export function syntaxDecorationExtensions( + options: { + active?: (language: string) => boolean; + query?: (doc: number, query: SyntaxDecorationQuery, signal: AbortSignal) => Promise<SyntaxDecorationBatch>; + } = {}, +): Extension { + const active = options.active ?? languageActive; + const query = options.query ?? hostDecorations; + return [ + marksField, + Prec.highest(EditorView.decorations.from(marksField)), + previewHighlights.of((state) => state.field(marksField, false) ?? Decoration.none), + EditorView.theme(syntaxTokenTheme()), + ViewPlugin.fromClass( + class { + private generation = 0; + private destroyed = false; + private running: AbortController | null = null; + private readonly schedule = debounce(() => void this.run(), 50); + constructor(private readonly view: EditorView) { + this.refresh(); + } + update(update: ViewUpdate) { + if (this.destroyed) return; + const forced = update.transactions.some((tr) => + tr.effects.some((effect) => effect.is(syntaxDecorationsRefresh)), + ); + const treeChanged = syntaxTree(update.startState) !== syntaxTree(update.state); + if (forced || shownAgain(update) || update.docChanged || update.viewportChanged || treeChanged) + this.refresh(); + } + destroy() { + this.destroyed = true; + this.generation += 1; + this.schedule.cancel?.(); + this.running?.abort(); + } + private refresh() { + if (this.destroyed) return; + this.generation++; + this.running?.abort(); + this.schedule.cancel(); + const language = docOf(this.view)?.language; + const hasMarks = this.view.state.field(marksField).size !== 0; + if ((language && active(language)) || hasMarks) this.schedule(); + } + /** False once the view is gone or a newer refresh has started. */ + private canApply(generation: number): boolean { + return !this.destroyed && generation === this.generation; + } + private apply(generation: number, marks: DecorationSet): void { + if (!this.canApply(generation)) return; + try { + this.view.dispatch({ effects: setMarks.of(marks) }); + } catch { + // CodeMirror rejects dispatch on a view destroyed during this turn. + } + } + private clear(generation: number): void { + if (!this.canApply(generation)) return; + try { + if (!this.view.state.field(marksField).size) return; + this.apply(generation, Decoration.none); + } catch { + // Reading state after destroy throws; there is nothing left to clear. + } + } + private async run() { + if (this.destroyed) return; + const view = this.view; + const generation = this.generation; + const doc = docOf(view); + const clear = () => this.clear(generation); + if (!view.dom.isConnected || !doc || doc.virtual || doc.large || !active(doc.language)) { + clear(); + return; + } + const state = view.state; + const owner = pluginEpoch; + const current = () => + this.canApply(generation) && owner === pluginEpoch && view.dom.isConnected && view.state.doc === state.doc; + const running = (this.running = new AbortController()); + let batch: SyntaxDecorationBatch; + try { + await whenSynced(view); + if (!current()) return; + const spans = syntaxDecorationSpans(state, view.visibleRanges); + const nodes = syntaxSnapshot(state, spans); + if (!nodes.length) { + clear(); + return; + } + const ranges = spans.map((span) => offsetsToRange(state.doc, span.from, span.to)); + batch = await query(doc.doc, { ranges, nodes, epoch: generation }, running.signal); + } catch { + if (current()) clear(); + return; + } finally { + if (this.running === running) this.running = null; + } + if (!current() || batch.epoch !== generation) return; + if (batch.stale) { + this.refresh(); + return; + } + this.apply(generation, syntaxDecorationSet(view.state.doc, batch.marks)); + } + }, + ), + ]; +} + +function poke(clear = false) { + for (const editor of useEditorRegistry.getState().editors) { + try { + const refresh = syntaxDecorationsRefresh.of(null); + editor.view.dispatch({ effects: clear ? [setMarks.of(Decoration.none), refresh] : refresh }); + } catch { + // The editor can close while a plugin list reload is in flight. + } + } +} + +/** Loads the provider list and drops marks when plugins or their settings change. */ +export function startPluginSyntaxDecorations(): () => void { + let disposed = false; + const reload = () => { + const epoch = pluginEpoch; + void hostLanguages().then((next) => { + if (disposed || epoch !== pluginEpoch) return; + languages = next; + poke(); + }); + }; + const offPlugins = usePlugins.subscribe((state, prev) => { + if (state.plugins === prev.plugins) return; + syntaxDecorationPluginsChanged(); + reload(); + }); + const offSettings = + isTauri() || hasInvokeRoute() + ? onIdeEvent("settingsChanged", (event) => { + if (event.key.startsWith("appearance.") || event.key.includes("theme") || event.key.includes("colorScheme")) + return; + poke(); + }) + : () => {}; + const off = registerEditorContribution({ + id: "plugins.syntaxDecorations", + extensions: (ctx) => (ctx.virtual || ctx.large ? [] : syntaxDecorationExtensions()), + }); + reload(); + return () => { + disposed = true; + offPlugins(); + offSettings(); + off(); + syntaxDecorationPluginsChanged(); + }; +} diff --git a/src/features/plugins/syntaxSnapshot.ts b/src/features/plugins/syntaxSnapshot.ts new file mode 100644 index 0000000000..15f7620836 --- /dev/null +++ b/src/features/plugins/syntaxSnapshot.ts @@ -0,0 +1,75 @@ +/** + * A bounded slice of the editor's existing Lezer tree for a plugin. The host + * does not parse. Node names belong to the parser that produced the tree. + */ +import { syntaxTree } from "@codemirror/language"; +import type { EditorState } from "@codemirror/state"; +import { offsetsToRange } from "@/editor/lsp/positions"; +import type { SyntaxNodeSnapshot } from "@/bindings"; + +export const MAX_SYNTAX_NODES = 8192; +export const MAX_SYNTAX_RANGES = 32; + +export interface SyntaxSpan { + from: number; + to: number; +} + +export type { SyntaxNodeSnapshot }; + +function overlaps(from: number, to: number, spans: readonly SyntaxSpan[]): boolean { + return spans.some((span) => from < span.to && to > span.from); +} + +/** Nodes that overlap `spans`, plus their ancestors, capped at `limit`. */ +export function syntaxSnapshot( + state: EditorState, + spans: readonly SyntaxSpan[], + limit = MAX_SYNTAX_NODES, +): SyntaxNodeSnapshot[] { + const wanted = spans + .filter((span) => span.from < span.to && span.to > 0 && span.from < state.doc.length) + .slice(0, MAX_SYNTAX_RANGES); + if (!wanted.length || limit <= 0) return []; + const seen = new Map<string, number>(); + const nodes: { from: number; to: number; name: string; parent: number | null }[] = []; + const stop = new Error("syntax snapshot limit"); + const take = (span: SyntaxSpan) => { + const ancestors: number[] = []; + syntaxTree(state).iterate({ + from: Math.max(0, span.from), + to: Math.min(state.doc.length, span.to), + enter(ref) { + const { from, to, name, type } = ref; + if (!overlaps(from, to, wanted)) return false; + const parent = ancestors.at(-1) ?? null; + const key = `${parent}/${type.id}/${from}/${to}/${name}`; + let index = seen.get(key); + if (index === undefined) { + index = nodes.length; + seen.set(key, index); + nodes.push({ from, to, name, parent }); + if (nodes.length >= limit) throw stop; + } + ancestors.push(index); + }, + leave() { + ancestors.pop(); + }, + }); + }; + try { + for (const span of wanted) take(span); + } catch (err) { + if (err !== stop) throw err; + } + const order = nodes + .map((node, index) => ({ ...node, index })) + .sort((a, b) => a.from - b.from || a.to - b.to || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); + const index = new Map(order.map((node, i) => [node.index, i])); + return order.map(({ name, from, to, parent }) => ({ + name, + range: offsetsToRange(state.doc, from, to), + parent: parent === null ? null : index.get(parent)!, + })); +} diff --git a/src/styles/global.css b/src/styles/global.css index 772b20a8b5..0a2eaa9221 100644 --- a/src/styles/global.css +++ b/src/styles/global.css @@ -314,3 +314,13 @@ a:hover { :root[data-aa-editor="none"] .cm-editor { -webkit-font-smoothing: none; } + +/* Plugin foreground pairs. The mark sets only these two variables; this rule + is the only place that turns them into a colour. Light uses the light pair. + Dark and high-contrast dark use the dark pair. */ +.cm-plugin-fg { + color: var(--plugin-fg-dark); +} +:root[data-theme="light"] .cm-plugin-fg { + color: var(--plugin-fg-light); +} diff --git a/wit/plugin.wit b/wit/plugin.wit index af3b122631..e802e21e13 100644 --- a/wit/plugin.wit +++ b/wit/plugin.wit @@ -232,3 +232,8 @@ world run-configuration-completion-exports { export run-configuration-completion world plugin-search { include plugin; export search-provider; } /// Optional export composed with the base plugin by the SDK. world search { export search-provider; } + +/// A plugin that paints theme-token foreground marks from a syntax snapshot (API 1.20). +world plugin-syntax-decorations { include plugin; export syntax-decorations-provider; } +/// Export-only syntax decorations, composed with the base plugin world. +world syntax-decorations { export syntax-decorations-provider; } diff --git a/wit/syntax-decorations.wit b/wit/syntax-decorations.wit new file mode 100644 index 0000000000..3c5bdb4c32 --- /dev/null +++ b/wit/syntax-decorations.wit @@ -0,0 +1,69 @@ +package openidea:plugin@1.20.0; + +/// Optional export (world `plugin-syntax-decorations`): foreground marks for +/// documents of the languages declared with the `syntax-decorations` provider +/// kind. The host sends the ranges it is painting and a bounded slice of the +/// editor's existing syntax tree. The plugin does not parse, and the host does +/// not run a second parser. +/// +/// Node `name`s come from that editor's parser. They are not a stable +/// vocabulary across languages or parser implementations. Ranges use the +/// shared UTF-16 `types.range` (0-based line, UTF-16 column). +/// +/// A mark paints its `foreground` colours when it has them, otherwise its +/// `token`: `rainbow-1` … `rainbow-5`, which the host maps onto the theme's +/// existing `--syn-rainbow-1` … `--syn-rainbow-5` colours. A mark with an +/// invalid colour or an unknown token is dropped. Only the foreground changes. +/// API 1.20. +interface syntax-decorations-provider { + use types.{range}; + + /// The open editor the host is asking about. `version` is the host + /// buffer version at the start of this call. + record document { + path: string, + language: string, + version: u64, + } + + /// One node of the editor's current syntax tree. `parent` is an index + /// into `decoration-request.nodes`. Index 0 is a real node. The index + /// may be greater than the child's, because the list is ordered by + /// position, not parent-before-child. `parent` is none when that + /// ancestor was not included: the tree may be partial, and the node + /// budget can drop an ancestor while keeping the child. None does not + /// mean the node is the root of the real tree. `name` belongs to the + /// editor's parser and is not stable across parsers. + record syntax-node { + name: string, + range: range, + parent: option<u32>, + } + + record decoration-request { + document: document, + /// Ranges the host wants marks for (visible ranges and sticky header + /// lines). At most 32. + ranges: list<range>, + /// At most 8192 nodes. + nodes: list<syntax-node>, + } + + /// Foreground colours of a mark: `#rrggbb`, or `#rrggbbaa` with an alpha + /// (`ff` fully opaque), one for dark themes and one for light themes. + record syntax-foreground { + dark: string, + light: string, + } + + /// A foreground mark. `token` is `rainbow-1` … `rainbow-5`, and may be + /// empty when `foreground` is set. + record syntax-mark { + range: range, + token: string, + foreground: option<syntax-foreground>, + } + + /// Marks for `request`, under the edit-path budget. At most 10,000 are kept. + syntax-decorations: func(request: decoration-request) -> list<syntax-mark>; +}