diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 0000000000..4194c03795 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Formatting-only commits, skipped by `git blame` (GitHub applies this file +# automatically; locally: git config blame.ignoreRevsFile .git-blame-ignore-revs). + +# style: cargo fmt --all +b9b520d74562afa6e7f32606df5d3e480604639d diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5c2bdbb32..9456f27c3e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,6 +12,30 @@ on: - main jobs: + lint: + name: Format and Clippy + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + submodules: true + + - name: Set up Rust + uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + + - name: Cache dependencies + uses: Swatinem/rust-cache@v2 + + - name: Check formatting + run: cargo fmt --all --check + + - name: Clippy + run: cargo clippy --workspace --all-targets -- -D warnings + build-native: name: Build and Test (Native) runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index eb7860fb4b..9830abe8da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -65,3 +65,8 @@ members = [ resolver = "2" exclude = ["turtle"] +[workspace.lints.clippy] +# Bevy systems take their data as parameters, so system signatures naturally +# have many parameters and nested `Query<(…), (…)>` types. +type_complexity = "allow" +too_many_arguments = "allow" diff --git a/components-rs/Cargo.toml b/components-rs/Cargo.toml index 018ae35c80..46e86e4034 100644 --- a/components-rs/Cargo.toml +++ b/components-rs/Cargo.toml @@ -35,3 +35,6 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = tr anyhow = { version = "1", optional = true } rdf-parsers.workspace = true url = "2" + +[lints] +workspace = true diff --git a/components-rs/src/components/registry.rs b/components-rs/src/components/registry.rs index 32ee50ca82..13ac70e593 100644 --- a/components-rs/src/components/registry.rs +++ b/components-rs/src/components/registry.rs @@ -138,6 +138,12 @@ struct CollectedNode { resolver: ContextResolver, } +impl Default for ComponentRegistry { + fn default() -> Self { + Self::new() + } +} + impl ComponentRegistry { pub fn new() -> Self { Self { @@ -162,8 +168,7 @@ impl ComponentRegistry { state: &ModuleState, ) -> Result<()> { let mut all_nodes: HashMap = HashMap::new(); - let mut visited_files: std::collections::HashSet = - std::collections::HashSet::new(); + let mut visited_files: std::collections::HashSet = std::collections::HashSet::new(); let mut id_spans: HashMap> = HashMap::new(); let mut id_source_files: HashMap = HashMap::new(); let mut file_sources: HashMap = HashMap::new(); @@ -187,10 +192,7 @@ impl ComponentRegistry { ) .await?; } else { - tracing::warn!( - "Component file does not exist: {}", - component_url.as_str() - ); + tracing::warn!("Component file does not exist: {}", component_url.as_str()); } } } diff --git a/components-rs/src/components/types.rs b/components-rs/src/components/types.rs index 34a125bc2a..6de22ba642 100644 --- a/components-rs/src/components/types.rs +++ b/components-rs/src/components/types.rs @@ -12,10 +12,8 @@ use std::ops::Range; use rdf_parsers::jsonld::convert::JsonLdVal; -pub const PREFIX_OO: &str = - "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#"; -pub const PREFIX_OM: &str = - "https://linkedsoftwaredependencies.org/vocabularies/object-mapping#"; +pub const PREFIX_OO: &str = "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#"; +pub const PREFIX_OM: &str = "https://linkedsoftwaredependencies.org/vocabularies/object-mapping#"; pub const PREFIX_RDF: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; pub const PREFIX_RDFS: &str = "http://www.w3.org/2000/01/rdf-schema#"; pub const PREFIX_XSD: &str = "http://www.w3.org/2001/XMLSchema#"; diff --git a/components-rs/src/config/registry.rs b/components-rs/src/config/registry.rs index baaf9f50ff..71f3e22989 100644 --- a/components-rs/src/config/registry.rs +++ b/components-rs/src/config/registry.rs @@ -34,6 +34,12 @@ pub struct ConfigRegistry { pub configs: Vec, } +impl Default for ConfigRegistry { + fn default() -> Self { + Self::new() + } +} + impl ConfigRegistry { pub fn new() -> Self { Self { @@ -76,7 +82,8 @@ impl ConfigRegistry { let mut id_spans: HashMap> = HashMap::new(); collect_id_spans(&doc, &resolver, &mut id_spans); - self.process_imports(fs, &doc, &resolver, state, url).await?; + self.process_imports(fs, &doc, &resolver, state, url) + .await?; let entries: Vec<&JsonLdVal> = if let Some(graph) = doc.get("@graph") { match graph.as_array() { diff --git a/components-rs/src/context/expand.rs b/components-rs/src/context/expand.rs index 75463405b5..49dfd9419a 100644 --- a/components-rs/src/context/expand.rs +++ b/components-rs/src/context/expand.rs @@ -92,7 +92,11 @@ impl ContextResolver { Ok(()) } - fn load_context_object(&mut self, obj: &JsonLdVal, known_contexts: &HashMap) -> Result<()> { + fn load_context_object( + &mut self, + obj: &JsonLdVal, + known_contexts: &HashMap, + ) -> Result<()> { let members = obj .as_object() .ok_or_else(|| ComponentsJsError::ContextResolution("Expected object".into()))?; @@ -124,8 +128,10 @@ impl ContextResolver { if let Some(id) = val.get("@id").and_then(|v| v.as_str()) { let type_coercion = val.get("@type").and_then(|v| v.as_str()).map(String::from); - let container = - val.get("@container").and_then(|v| v.as_str()).map(String::from); + let container = val + .get("@container") + .and_then(|v| v.as_str()) + .map(String::from); self.terms.insert( key.clone(), TermDef { @@ -196,7 +202,7 @@ impl ContextResolver { let expanded_base = self.expand_term(base_iri); if let Some(suffix) = iri.strip_prefix(expanded_base.as_str()) { let base_len = expanded_base.len(); - if best.as_ref().is_none_or(|(_, bl)| base_len > *bl) { + if best.as_ref().map_or(true, |(_, bl)| base_len > *bl) { best = Some((format!("{prefix}:{suffix}"), base_len)); } } @@ -249,7 +255,7 @@ impl IriCompactor { (name.clone(), expanded) }) .collect(); - prefixes.sort_by(|a, b| b.1.len().cmp(&a.1.len())); + prefixes.sort_by_key(|p| std::cmp::Reverse(p.1.len())); let terms: Vec<(String, String)> = resolver .terms @@ -411,7 +417,8 @@ mod tests { use rdf_parsers::jsonld::convert::parse_json; fn make_cjs_context() -> HashMap { - let ctx_json = parse_json(r#"{ + let ctx_json = parse_json( + r#"{ "@context": { "oo": "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#", "Module": { "@id": "oo:Module" }, @@ -426,7 +433,8 @@ mod tests { "requireElement": { "@id": "oo:componentPath" }, "import": { "@id": "rdfs:seeAlso", "@type": "@id" } } - }"#) + }"#, + ) .unwrap(); let mut known = HashMap::new(); known.insert( @@ -473,8 +481,14 @@ mod tests { ]"#).unwrap(); let resolver = ContextResolver::from_context_value(&ctx_ref, &known).unwrap(); - assert_eq!(resolver.expand_term("ex:MyModule"), "http://example.org/MyModule"); - assert_eq!(resolver.expand_term("hello:say"), "http://example.org/hello/say"); + assert_eq!( + resolver.expand_term("ex:MyModule"), + "http://example.org/MyModule" + ); + assert_eq!( + resolver.expand_term("hello:say"), + "http://example.org/hello/say" + ); } #[test] @@ -508,7 +522,10 @@ mod tests { let nodes = extract_graph_nodes(&doc, &known).unwrap(); assert_eq!(nodes.len(), 1); let module = &nodes[0]; - assert_eq!(module.id.as_deref(), Some("http://example.org/HelloWorldModule")); + assert_eq!( + module.id.as_deref(), + Some("http://example.org/HelloWorldModule") + ); assert_eq!( module.types, vec!["https://linkedsoftwaredependencies.org/vocabularies/object-oriented#Module"] @@ -518,10 +535,13 @@ mod tests { #[test] fn test_vocab_expansion() { let known = HashMap::new(); - let ctx = parse_json(r#"{ + let ctx = parse_json( + r#"{ "@vocab": "https://linkedsoftwaredependencies.org/vocabularies/object-oriented#", "ex": "http://example.org/" - }"#).unwrap(); + }"#, + ) + .unwrap(); let resolver = ContextResolver::from_context_value(&ctx, &known).unwrap(); assert_eq!( diff --git a/components-rs/src/discovery/node_modules.rs b/components-rs/src/discovery/node_modules.rs index b8ca4ea33e..a60105030f 100644 --- a/components-rs/src/discovery/node_modules.rs +++ b/components-rs/src/discovery/node_modules.rs @@ -21,11 +21,7 @@ pub fn build_node_module_import_paths(main_module_path: &Url) -> Vec { let mut paths = Vec::new(); let mut current = main_module_path.clone(); paths.push(current.clone()); - loop { - let parent = match current.join("..") { - Ok(p) => p, - Err(_) => break, - }; + while let Ok(parent) = current.join("..") { if parent == current { break; } @@ -35,11 +31,7 @@ pub fn build_node_module_import_paths(main_module_path: &Url) -> Vec { // findFiles to scan the entire filesystem, which hangs the build. // Two non-empty path segments (/home/user/) is the practical floor // for any project-relevant node_modules location. - let depth = current - .path() - .split('/') - .filter(|s| !s.is_empty()) - .count(); + let depth = current.path().split('/').filter(|s| !s.is_empty()).count(); if depth < 2 { break; } @@ -78,7 +70,10 @@ pub async fn build_node_module_paths( result.len(), ); } - tracing::info!("[node_modules] build_node_module_paths returning {} paths", result.len()); + tracing::info!( + "[node_modules] build_node_module_paths returning {} paths", + result.len() + ); Ok(result) } @@ -92,16 +87,20 @@ async fn scan_import_path( visited: &mut HashSet, recursive: bool, ) -> Result<()> { - let flat = fs.glob(import_path, "node_modules/*/package.json") + let flat = fs + .glob(import_path, "node_modules/*/package.json") .await .unwrap_or_default(); - let scoped = fs.glob(import_path, "node_modules/@*/*/package.json") + let scoped = fs + .glob(import_path, "node_modules/@*/*/package.json") .await .unwrap_or_default(); tracing::info!( "[node_modules] scan_import_path {}: flat={} scoped={}", - import_path.as_str(), flat.len(), scoped.len(), + import_path.as_str(), + flat.len(), + scoped.len(), ); let mut added = 0usize; @@ -110,7 +109,10 @@ async fn scan_import_path( // from the glob result. Using rfind('/') is unambiguous; url.join(".") // can misbehave depending on whether the URL has a trailing slash. let Some(pkg_dir) = package_json_url_to_dir(&entry.path) else { - tracing::warn!("[node_modules] failed to derive dir from {}", entry.path.as_str()); + tracing::warn!( + "[node_modules] failed to derive dir from {}", + entry.path.as_str() + ); continue; }; if visited.insert(pkg_dir.clone()) { @@ -121,7 +123,11 @@ async fn scan_import_path( } } } - tracing::info!("[node_modules] scan_import_path {} added {} new packages", import_path.as_str(), added); + tracing::info!( + "[node_modules] scan_import_path {} added {} new packages", + import_path.as_str(), + added + ); Ok(()) } @@ -143,19 +149,16 @@ mod tests { #[test] fn test_package_json_url_to_dir() { - let flat = Url::parse( - "file:///home/user/project/node_modules/lodash/package.json", - ) - .unwrap(); + let flat = + Url::parse("file:///home/user/project/node_modules/lodash/package.json").unwrap(); assert_eq!( package_json_url_to_dir(&flat).unwrap().as_str(), "file:///home/user/project/node_modules/lodash/", ); - let scoped = Url::parse( - "file:///home/user/project/node_modules/%40types/node/package.json", - ) - .unwrap(); + let scoped = + Url::parse("file:///home/user/project/node_modules/%40types/node/package.json") + .unwrap(); assert_eq!( package_json_url_to_dir(&scoped).unwrap().as_str(), "file:///home/user/project/node_modules/%40types/node/", diff --git a/components-rs/src/discovery/package_json.rs b/components-rs/src/discovery/package_json.rs index 3016d4255c..fe745f1d85 100644 --- a/components-rs/src/discovery/package_json.rs +++ b/components-rs/src/discovery/package_json.rs @@ -96,13 +96,20 @@ pub async fn read_package_jsons( fs: &dyn Fs, module_paths: &[Url], ) -> Result> { - tracing::info!("[package_json] read_package_jsons called with {} paths", module_paths.len()); + tracing::info!( + "[package_json] read_package_jsons called with {} paths", + module_paths.len() + ); let mut result = HashMap::new(); for module_path in module_paths { let pkg_url = match module_path.join("package.json") { Ok(u) => u, Err(e) => { - tracing::warn!("[package_json] failed to join package.json onto {}: {}", module_path.as_str(), e); + tracing::warn!( + "[package_json] failed to join package.json onto {}: {}", + module_path.as_str(), + e + ); continue; } }; @@ -122,7 +129,10 @@ pub async fn read_package_jsons( }; result.insert(module_path.clone(), pkg); } - tracing::info!("[package_json] read_package_jsons parsed {} package.json files", result.len()); + tracing::info!( + "[package_json] read_package_jsons parsed {} package.json files", + result.len() + ); Ok(result) } diff --git a/conformance/Cargo.toml b/conformance/Cargo.toml index a5f7307359..e20f78cff7 100644 --- a/conformance/Cargo.toml +++ b/conformance/Cargo.toml @@ -22,3 +22,6 @@ sophia_api.workspace = true sophia_iri.workspace = true sophia_turtle = "0.9.0" sophia_inmem = "0.9.0" + +[lints] +workspace = true diff --git a/conformance/build.rs b/conformance/build.rs index 8fb64517e2..f0f9f8106e 100644 --- a/conformance/build.rs +++ b/conformance/build.rs @@ -102,6 +102,8 @@ fn sanitize_test_name(original: &str, existing: &mut HashSet) -> String make_unique(s, existing) } +// Mirrors the manifest entry; not every field is used to generate tests. +#[allow(dead_code)] #[derive(Debug)] struct TurtleEval { name: String, @@ -146,6 +148,7 @@ pub fn {}() {{ } } +#[allow(dead_code)] #[derive(Debug)] struct TurtleSyntax { name: String, diff --git a/conformance/src/lib.rs b/conformance/src/lib.rs index b6469ac787..3d0ed96e32 100644 --- a/conformance/src/lib.rs +++ b/conformance/src/lib.rs @@ -51,7 +51,7 @@ pub fn test_syntax(location: &str, is_positive: bool) { "Failed to parse turtle\n{}\n\nErrors {:?}", turtle_source, errors ); - assert!(false, "Parsing failed, and shouldn't have failed"); + panic!("Parsing failed, and shouldn't have failed"); } } else { if errors.is_empty() && turtle.is_some() && defined_prefixes { @@ -60,7 +60,7 @@ pub fn test_syntax(location: &str, is_positive: bool) { turtle_source ); - assert!(false, "Parsing succeeded, and should have failed"); + panic!("Parsing succeeded, and should have failed"); } } } diff --git a/conformance/src/main.rs b/conformance/src/main.rs index fedfe43886..9fd3f9b3c4 100644 --- a/conformance/src/main.rs +++ b/conformance/src/main.rs @@ -23,7 +23,7 @@ fn sorted_file_paths_by_size_desc(dir: impl AsRef) -> std::io::Result>(); - files.sort_by(|a, b| b.1.cmp(&a.1)); + files.sort_by_key(|f| std::cmp::Reverse(f.1)); Ok(files.into_iter().map(|(path, _)| path).collect()) } diff --git a/core/Cargo.toml b/core/Cargo.toml index 58d40ad5e4..5a1ea01d04 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -63,3 +63,6 @@ mie = { version = "=0.2.9", default-features = false } [package.metadata.cargo-machete] # Intentionally-unused version pins (see sparql_service / mie above). ignored = ["sparql_service", "mie"] + +[lints] +workspace = true diff --git a/core/src/backend.rs b/core/src/backend.rs index da10b870ab..06b33da810 100644 --- a/core/src/backend.rs +++ b/core/src/backend.rs @@ -1,18 +1,16 @@ -use std::{collections::HashMap, sync::Arc}; +use std::collections::HashMap; +use crate::text::LineIndex; use bevy_ecs::{ bundle::Bundle, component::Component, - entity::Entity, schedule::ScheduleLabel, world::{CommandQueue, World}, }; use completion::CompletionRequest; -use futures::lock::Mutex; use goto_type::GotoTypeRequest; use references::ReferencesRequest; use request::{GotoTypeDefinitionParams, GotoTypeDefinitionResponse}; -use crate::text::LineIndex; use tracing::{debug, error, info, instrument, warn}; use crate::{ @@ -44,7 +42,6 @@ pub type Result = std::result::Result; /// (the `swls` binary's `tower_lsp` adapter, or a future wasm dispatcher) call these /// directly. It is generic over the [`Client`] used to send server-to-client messages. pub struct Backend { - entities: Arc>>, sender: CommandSender, client: C, semantic_tokens: Vec, @@ -61,7 +58,6 @@ impl std::fmt::Debug for Backend { impl Backend { pub fn new(sender: CommandSender, client: C, tokens: Vec) -> Self { Self { - entities: Default::default(), sender, client, semantic_tokens: tokens, @@ -76,7 +72,7 @@ impl Backend { let mut commands = CommandQueue::default(); commands.push(move |world: &mut World| { let o = f(world); - if let Err(_) = tx.send(o) { + if tx.send(o).is_err() { error!("Failed to run schedule for {}", stringify!(T)); }; }); @@ -89,9 +85,15 @@ impl Backend { rx.await.ok() } + /// Run `schedule` for the document at `url` with the request component(s) + /// `param`, and take the response component `T`. + /// + /// The document is looked up inside the world, in the same step that runs + /// the schedule, so a document closed in between cannot be used after it + /// is gone. `None` when there is no such document. async fn run_schedule( &self, - entity: Entity, + url: Url, schedule: impl ScheduleLabel + Clone, param: impl Bundle, ) -> Option { @@ -99,9 +101,14 @@ impl Backend { let mut commands = CommandQueue::default(); commands.push(move |world: &mut World| { + let Some(entity) = find_document(world, &url) else { + debug!("No document {}", url); + let _ = tx.send(None); + return; + }; world.entity_mut(entity).insert(param); world.run_schedule(schedule.clone()); - if let Err(_) = tx.send(world.entity_mut(entity).take::()) { + if tx.send(world.entity_mut(entity).take::()).is_err() { error!(name: "Failed to run schedule", "Failed to run schedule {:?}", schedule); }; }); @@ -114,9 +121,10 @@ impl Backend { rx.await.unwrap_or_default() } - async fn get_entity(&self, uri: &str) -> Option { - let map = self.entities.lock().await; - map.get(uri).copied() + /// The document a request is about. Requests refer to documents by URL; + /// the entity is looked up when the request runs (see [`Self::run_schedule`]). + async fn document(&self, uri: &str) -> Option { + Url::parse(uri).ok() } /// Whether the given LSP feature has been disabled via [`ServerConfig`]. @@ -131,10 +139,6 @@ impl Backend { .await .unwrap_or(false) } - - fn adjust_position(pos: &mut Position) { - pos.character = pos.character.saturating_sub(1); - } } impl Backend { @@ -201,20 +205,21 @@ impl Backend { Ok(InitializeResult { server_info: None, capabilities: ServerCapabilities { - inlay_hint_provider: is_enabled(Disabled::InlayHint) - .then_some(OneOf::Left(true)), + inlay_hint_provider: is_enabled(Disabled::InlayHint).then_some(OneOf::Left(true)), text_document_sync: Some(TextDocumentSyncCapability::Kind( TextDocumentSyncKind::FULL, )), code_action_provider: is_enabled(Disabled::CodeAction) .then_some(CodeActionProviderCapability::Simple(true)), - completion_provider: is_enabled(Disabled::Completion).then_some(CompletionOptions { - resolve_provider: Some(false), - trigger_characters: Some(vec![String::from(":")]), - work_done_progress_options: Default::default(), - all_commit_characters: None, - completion_item: None, - }), + completion_provider: is_enabled(Disabled::Completion).then_some( + CompletionOptions { + resolve_provider: Some(false), + trigger_characters: Some(vec![String::from(":")]), + work_done_progress_options: Default::default(), + all_commit_characters: None, + completion_item: None, + }, + ), // implementation_provider: Some(ImplementationProviderCapability::Simple(true)), type_definition_provider: is_enabled(Disabled::GotoTypeDefinition) .then_some(TypeDefinitionProviderCapability::Simple(true)), @@ -274,7 +279,10 @@ impl Backend { .await; } - pub async fn did_change_workspace_folders(&self, params: DidChangeWorkspaceFoldersParams) -> () { + pub async fn did_change_workspace_folders( + &self, + params: DidChangeWorkspaceFoldersParams, + ) -> () { self.run(move |world| { let mut config = world.resource_mut::(); let WorkspaceFoldersChangeEvent { added, removed } = params.event; @@ -289,7 +297,6 @@ impl Backend { config.workspaces.extend(added); }) .await; - () } #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))] @@ -302,13 +309,13 @@ impl Backend { return Ok(None); } let uri = params.text_document.uri.as_str(); - let Some(entity) = self.get_entity(uri).await else { - debug!("Didn't find entity {} stopping", uri); + let Some(doc) = self.document(uri).await else { + debug!("No document {}", uri); return Ok(None); }; if let Some(res) = self - .run_schedule::(entity, SemanticLabel, HighlightRequest(vec![])) + .run_schedule::(doc, SemanticLabel, HighlightRequest(vec![])) .await { Ok(Some(SemanticTokensResult::Tokens( @@ -335,19 +342,18 @@ impl Backend { if self.is_disabled(Disabled::References).await { return Ok(None); } - let Some(entity) = self - .get_entity(params.text_document_position.text_document.uri.as_str()) + let Some(doc) = self + .document(params.text_document_position.text_document.uri.as_str()) .await else { return Ok(None); }; - let mut pos = params.text_document_position.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position.position; let arr = self .run_schedule::( - entity, + doc, ReferencesLabel, (PositionComponent(pos), ReferencesRequest(Vec::new())), ) @@ -365,19 +371,14 @@ impl Backend { if self.is_disabled(Disabled::Rename).await { return Ok(None); } - let Some(entity) = self.get_entity(params.text_document.uri.as_str()).await else { + let Some(doc) = self.document(params.text_document.uri.as_str()).await else { return Ok(None); }; - let mut pos = params.position; - Self::adjust_position(&mut pos); + let pos = params.position; let resp = self - .run_schedule::( - entity, - PrepareRenameLabel, - PositionComponent(pos), - ) + .run_schedule::(doc, PrepareRenameLabel, PositionComponent(pos)) .await .map(|x| PrepareRenameResponse::RangeWithPlaceholder { range: x.range, @@ -392,20 +393,19 @@ impl Backend { if self.is_disabled(Disabled::Rename).await { return Ok(Some(WorkspaceEdit::new(HashMap::new()))); } - let Some(entity) = self - .get_entity(params.text_document_position.text_document.uri.as_str()) + let Some(doc) = self + .document(params.text_document_position.text_document.uri.as_str()) .await else { return Ok(None); }; - let mut pos = params.text_document_position.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position.position; let mut change_map: HashMap> = HashMap::new(); if let Some(changes) = self .run_schedule::( - entity, + doc, RenameLabel, ( PositionComponent(pos), @@ -428,8 +428,8 @@ impl Backend { } let request: HoverRequest = HoverRequest::default(); - let Some(entity) = self - .get_entity( + let Some(doc) = self + .document( params .text_document_position_params .text_document @@ -441,15 +441,14 @@ impl Backend { return Ok(None); }; - let mut pos = params.text_document_position_params.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position_params.position; if let Some(hover) = self - .run_schedule::(entity, HoverLabel, (request, PositionComponent(pos))) + .run_schedule::(doc, HoverLabel, (request, PositionComponent(pos))) .await { tracing::debug!("hover returned {} items", hover.0.len()); - if hover.0.len() > 0 { + if !hover.0.is_empty() { return Ok(Some(crate::lsp_types::Hover { contents: crate::lsp_types::HoverContents::Markup(MarkupContent { kind: MarkupKind::Markdown, @@ -469,13 +468,13 @@ impl Backend { return Ok(None); } let uri = params.text_document.uri.as_str(); - let Some(entity) = self.get_entity(uri).await else { - debug!("Didn't find entity {}", uri); + let Some(doc) = self.document(uri).await else { + debug!("No document {}", uri); return Ok(None); }; let request = self - .run_schedule::(entity, InlayLabel, InlayRequest::default()) + .run_schedule::(doc, InlayLabel, InlayRequest::default()) .await; debug!( @@ -483,22 +482,25 @@ impl Backend { request.as_ref().map(|x| x.0.len()).unwrap_or(0) ); - Ok(request.and_then(|x| Some(x.0))) + Ok(request.map(|x| x.0)) } #[instrument(skip(self))] - pub async fn formatting(&self, params: DocumentFormattingParams) -> Result>> { + pub async fn formatting( + &self, + params: DocumentFormattingParams, + ) -> Result>> { if self.is_disabled(Disabled::Format).await { return Ok(None); } let uri = params.text_document.uri.as_str(); - let Some(entity) = self.get_entity(uri).await else { - debug!("Didn't find entity {}", uri); + let Some(doc) = self.document(uri).await else { + debug!("No document {}", uri); return Ok(None); }; let request = self - .run_schedule::(entity, FormatLabel, FormatRequest(None)) + .run_schedule::(doc, FormatLabel, FormatRequest(None)) .await; Ok(request.and_then(|x| x.0)) } @@ -512,16 +514,16 @@ impl Backend { return Ok(None); } let uri = params.text_document_position.text_document.uri.as_str(); - let Some(entity) = self.get_entity(uri).await else { + let Some(doc) = self.document(uri).await else { return Ok(None); }; - // Use the exact position after the typed character — do NOT apply - // `adjust_position` here, the scan expects the cursor right after `:`. + // The exact position after the typed character: the scan expects the + // cursor right after `:`. let pos = params.text_document_position.position; let request = self .run_schedule::( - entity, + doc, OnTypeFormatLabel, ( PositionComponent(pos), @@ -537,13 +539,11 @@ impl Backend { let item = params.text_document; let url = item.uri.as_str().to_string(); - let entity = self - .run(|world| crate::document::open_document(world, item)) - .await; - - if let Some(entity) = entity { - self.entities.lock().await.insert(url, entity); - } + self.run(|world| { + crate::document::open_document(world, item); + }) + .await; + debug!("Opened {}", url); debug!("Requesting tokens refresh"); let _ = self.client.send_request::(()).await; @@ -558,7 +558,6 @@ impl Backend { #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))] pub async fn did_close(&self, params: DidCloseTextDocumentParams) { let url = params.text_document.uri; - self.entities.lock().await.remove(url.as_str()); let closed = { let url = url.clone(); @@ -581,8 +580,8 @@ impl Backend { #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))] pub async fn did_change(&self, params: DidChangeTextDocumentParams) { - let Some(entity) = self.get_entity(params.text_document.uri.as_str()).await else { - debug!("Didn't find entity {}", params.text_document.uri.as_str()); + let Some(doc) = self.document(params.text_document.uri.as_str()).await else { + debug!("No document {}", params.text_document.uri.as_str()); return; }; @@ -595,6 +594,10 @@ impl Backend { }; self.run(move |world| { + let Some(entity) = find_document(world, &doc) else { + debug!("No document {}", doc); + return; + }; let rope_c = RopeC(LineIndex::new(&change.text)); world .entity_mut(entity) @@ -625,8 +628,8 @@ impl Backend { if self.is_disabled(Disabled::GotoDefinition).await { return Ok(None); } - let Some(entity) = self - .get_entity( + let Some(doc) = self + .document( params .text_document_position_params .text_document @@ -638,12 +641,11 @@ impl Backend { return Ok(None); }; - let mut pos = params.text_document_position_params.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position_params.position; let arr = self .run_schedule::( - entity, + doc, GotoDefinitionLabel, (PositionComponent(pos), GotoDefinitionRequest(Vec::new())), ) @@ -664,8 +666,8 @@ impl Backend { if self.is_disabled(Disabled::GotoTypeDefinition).await { return Ok(None); } - let Some(entity) = self - .get_entity( + let Some(doc) = self + .document( params .text_document_position_params .text_document @@ -677,12 +679,11 @@ impl Backend { return Ok(None); }; - let mut pos = params.text_document_position_params.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position_params.position; let arr = self .run_schedule::( - entity, + doc, GotoTypeLabel, (PositionComponent(pos), GotoTypeRequest(Vec::new())), ) @@ -693,19 +694,22 @@ impl Backend { } #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))] - pub async fn code_action(&self, params: CodeActionParams) -> Result> { + pub async fn code_action( + &self, + params: CodeActionParams, + ) -> Result> { if self.is_disabled(Disabled::CodeAction).await { return Ok(None); } let uri = params.text_document.uri.as_str(); - let Some(entity) = self.get_entity(uri).await else { + let Some(doc) = self.document(uri).await else { return Ok(None); }; let pos = params.range.start; let request = self .run_schedule::( - entity, + doc, CodeActionLabel, (CodeActionRequest::default(), PositionComponent(pos)), ) @@ -773,21 +777,18 @@ impl Backend { if self.is_disabled(Disabled::Completion).await { return Ok(None); } - let Some(entity) = self - .get_entity(params.text_document_position.text_document.uri.as_str()) + let Some(doc) = self + .document(params.text_document_position.text_document.uri.as_str()) .await else { return Ok(None); }; - // Problem: when the cursor is at the end of an ident, that ident is not in range of the - // cursor - let mut pos = params.text_document_position.position; - Self::adjust_position(&mut pos); + let pos = params.text_document_position.position; let completions: Option> = self .run_schedule::( - entity, + doc, CompletionLabel, (CompletionRequest(vec![]), PositionComponent(pos)), ) diff --git a/core/src/components/config.rs b/core/src/components/config.rs index 567025cefa..3401128a43 100644 --- a/core/src/components/config.rs +++ b/core/src/components/config.rs @@ -79,10 +79,7 @@ pub enum Disabled { HoverShapeProperty, /// Hover explanation shown for a property that is only accepted because it /// is in the user's `allowed_properties` allow-list. - #[serde( - alias = "HOVER_EXCLUDED_PROPERTY", - alias = "hover_excluded_property" - )] + #[serde(alias = "HOVER_EXCLUDED_PROPERTY", alias = "hover_excluded_property")] HoverExcludedProperty, /// Master switch: disables `textDocument/definition` entirely (and stops diff --git a/core/src/components/document.rs b/core/src/components/document.rs index 44f409a649..44a95247e1 100644 --- a/core/src/components/document.rs +++ b/core/src/components/document.rs @@ -73,9 +73,89 @@ pub struct Snapshot(pub String); pub struct Global; /// [`Component`] containing the [`lsp_types::Url`] of the current document. -#[derive(Component, AsRef, Deref, AsMut, DerefMut, Debug)] +/// +/// Immutable: every document is indexed by its label in [`Documents`], which +/// component hooks keep up to date. Insert a new `Label` to relabel a document. +#[derive(Component, AsRef, Deref, Debug)] +#[component(immutable, on_insert = register_document, on_replace = unregister_document)] pub struct Label(pub crate::lsp_types::Url); +/// Every document in the world, by URL. +/// +/// Maintained by [`Label`]'s hooks, so it is correct however a document is +/// spawned, relabelled or despawned. Look documents up with +/// [`find_document`] rather than scanning labels. +/// +/// What kind of document an entity is follows from its markers: [`Open`] (the +/// editor has it), [`Background`] (the server loaded it), both (a background +/// document the user opened), and for a background document whether its URL +/// is in the ontology cache (`FsTrait::is_cache_url`). +#[derive(Resource, Debug, Default)] +pub struct Documents(std::collections::HashMap); + +impl Documents { + /// The document labelled `url`. + pub fn get(&self, url: &crate::lsp_types::Url) -> Option { + self.0.get(url).copied() + } + + /// Every document, by URL. + pub fn iter(&self) -> impl Iterator { + self.0.iter().map(|(u, e)| (u, *e)) + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } +} + +fn register_document( + mut world: bevy_ecs::world::DeferredWorld, + ctx: bevy_ecs::lifecycle::HookContext, +) { + let Some(url) = world.get::