From 028c9f7838e0c26b8753507056aa1ff7b8defb5b Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:43:13 +0000 Subject: [PATCH 01/10] chore: use only stable rustfmt options `imports_granularity` and `group_imports` need a nightly rustfmt, so on stable `cargo fmt` warned about them and could not reproduce the intended formatting. Keep `use_field_init_shorthand`, which is stable. --- rustfmt.toml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/rustfmt.toml b/rustfmt.toml index efd3c5ba44..e0c81ee235 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,3 +1,4 @@ -imports_granularity = "Crate" -group_imports = "StdExternalCrate" +# Only stable options, so `cargo fmt` gives the same result for every +# contributor and in CI. (`imports_granularity` and `group_imports` need a +# nightly rustfmt.) use_field_init_shorthand = true From b9b520d74562afa6e7f32606df5d3e480604639d Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:43:14 +0000 Subject: [PATCH 02/10] style: cargo fmt --all Formatting only, no code changes. Listed in .git-blame-ignore-revs. --- components-rs/src/components/registry.rs | 8 +--- components-rs/src/components/types.rs | 6 +-- components-rs/src/config/registry.rs | 3 +- components-rs/src/context/expand.rs | 40 +++++++++++++----- components-rs/src/discovery/node_modules.rs | 45 ++++++++++++--------- components-rs/src/discovery/package_json.rs | 16 ++++++-- core/src/backend.rs | 36 +++++++++++------ core/src/components/config.rs | 5 +-- core/src/feature/completion.rs | 2 +- core/src/feature/on_type_format.rs | 7 +--- core/src/feature/rename.rs | 14 ++++++- core/src/feature/semantic.rs | 7 +++- core/src/lib.rs | 2 +- core/src/prelude.rs | 7 ++-- core/src/systems/mod.rs | 20 ++++----- core/src/systems/namespace_properties.rs | 10 ++++- core/src/systems/prefix.rs | 2 +- core/src/systems/properties/systems.rs | 13 +++++- core/src/systems/shapes/mod.rs | 2 +- core/src/text.rs | 17 ++++++-- core/src/util/fs.rs | 2 +- e2e/src/lib.rs | 27 +++++++++---- e2e/tests/code_actions.rs | 22 +++++----- e2e/tests/diagnostics.rs | 10 ++++- e2e/tests/on_type_format.rs | 9 +++-- e2e/tests/prefix_diagnostics.rs | 29 ++++++------- e2e/tests/rename.rs | 10 +++-- e2e/tests/settings.rs | 20 +++++---- e2e/tests/turtle_completion.rs | 3 +- lang-jsonld/src/ecs/completion.rs | 10 +++-- lang-jsonld/src/ecs/mod.rs | 14 +++++-- lang-jsonld/src/lib.rs | 9 ++++- lang-n3/src/ecs/mod.rs | 5 +-- lang-rdf-base/src/code_actions.rs | 18 +++++---- lang-rdf-base/src/rename.rs | 3 +- lang-sparql/src/ecs/mod.rs | 14 ++++--- lang-trig/src/ecs/mod.rs | 5 ++- lang-turtle/src/ecs/code_action.rs | 6 ++- lang-turtle/src/ecs/completion.rs | 7 +--- lang-turtle/src/ecs/mod.rs | 3 +- swls/src/server.rs | 11 +---- 41 files changed, 312 insertions(+), 187 deletions(-) diff --git a/components-rs/src/components/registry.rs b/components-rs/src/components/registry.rs index 32ee50ca82..792727d634 100644 --- a/components-rs/src/components/registry.rs +++ b/components-rs/src/components/registry.rs @@ -162,8 +162,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 +186,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..f3a85df82c 100644 --- a/components-rs/src/config/registry.rs +++ b/components-rs/src/config/registry.rs @@ -76,7 +76,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..dfae5ddeec 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 { @@ -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..2dda257231 100644 --- a/components-rs/src/discovery/node_modules.rs +++ b/components-rs/src/discovery/node_modules.rs @@ -35,11 +35,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 +74,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 +91,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 +113,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 +127,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 +153,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/core/src/backend.rs b/core/src/backend.rs index da10b870ab..60142bac87 100644 --- a/core/src/backend.rs +++ b/core/src/backend.rs @@ -1,5 +1,6 @@ use std::{collections::HashMap, sync::Arc}; +use crate::text::LineIndex; use bevy_ecs::{ bundle::Bundle, component::Component, @@ -12,7 +13,6 @@ 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::{ @@ -201,20 +201,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 +275,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; @@ -487,7 +491,10 @@ impl Backend { } #[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); } @@ -693,7 +700,10 @@ 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); } 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/feature/completion.rs b/core/src/feature/completion.rs index 586983eb89..c7a8e0ad74 100644 --- a/core/src/feature/completion.rs +++ b/core/src/feature/completion.rs @@ -1,6 +1,6 @@ +use crate::lsp_types::{MarkupContent, MarkupKind}; use bevy_ecs::{prelude::*, schedule::ScheduleLabel}; use derive_more::{AsMut, AsRef, Deref, DerefMut}; -use crate::lsp_types::{MarkupContent, MarkupKind}; use crate::lsp_types::{ CompletionItem, CompletionItemKind, CompletionItemLabelDetails, CompletionTextEdit, diff --git a/core/src/feature/on_type_format.rs b/core/src/feature/on_type_format.rs index 1847643bab..7b42b30f70 100644 --- a/core/src/feature/on_type_format.rs +++ b/core/src/feature/on_type_format.rs @@ -18,12 +18,7 @@ use bevy_ecs::{prelude::*, schedule::ScheduleLabel}; use swls_lov::LocalPrefix; use tracing::instrument; -use crate::{ - lsp_types::TextEdit, - prelude::*, - systems::PrefixEntry, - util::position_to_offset, -}; +use crate::{lsp_types::TextEdit, prelude::*, systems::PrefixEntry, util::position_to_offset}; /// [`Component`] collecting the on-type-formatting [`TextEdit`]s for a request. #[derive(Component, Debug)] diff --git a/core/src/feature/rename.rs b/core/src/feature/rename.rs index dd156ebb8e..1d88637f2e 100644 --- a/core/src/feature/rename.rs +++ b/core/src/feature/rename.rs @@ -104,7 +104,16 @@ pub fn prepare_rename( } #[instrument(skip(query))] -pub fn rename(mut query: Query<(&TripleComponent, &Triples, &RopeC, &Label, &DynLang, &mut RenameEdits)>) { +pub fn rename( + mut query: Query<( + &TripleComponent, + &Triples, + &RopeC, + &Label, + &DynLang, + &mut RenameEdits, + )>, +) { for (triple, triples, rope, label, lang, mut edits) in &mut query { // Text RDF syntaxes rename via the model-based systems; skip them here. if lang.0.model_based_rename() { @@ -117,7 +126,8 @@ pub fn rename(mut query: Query<(&TripleComponent, &Triples, &RopeC, &Label, &Dyn // Collect unique byte-span ranges to avoid duplicate edits when the same // term appears as subject/predicate/object across multiple triples. - let mut seen_spans: std::collections::HashSet<(usize, usize)> = std::collections::HashSet::new(); + let mut seen_spans: std::collections::HashSet<(usize, usize)> = + std::collections::HashSet::new(); for quad in triples.0.iter() { for term in [quad.s(), quad.p(), quad.o()] { diff --git a/core/src/feature/semantic.rs b/core/src/feature/semantic.rs index b7d65530e1..cc03f5976e 100644 --- a/core/src/feature/semantic.rs +++ b/core/src/feature/semantic.rs @@ -138,7 +138,12 @@ pub fn semantic_tokens_system( advance(cur_byte, token.start, &mut cur_line, &mut cur_col); let start_line = cur_line; let start_col = cur_col; - let length = advance(token.start, token.start + token.length, &mut cur_line, &mut cur_col); + let length = advance( + token.start, + token.start + token.length, + &mut cur_line, + &mut cur_col, + ); cur_byte = token.start + token.length; let delta_line = start_line - pre_line; diff --git a/core/src/lib.rs b/core/src/lib.rs index edc9c99029..6e1e186a5a 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -81,9 +81,9 @@ //! use bevy_ecs::{prelude::*, schedule::ScheduleLabel}; +pub use lsp_types; use prelude::SemanticTokensDict; use systems::{init_ontology_extractor, populate_known_ontologies, OntologyExtractor}; -pub use lsp_types; use crate::prelude::*; diff --git a/core/src/prelude.rs b/core/src/prelude.rs index 33dc956c74..3a0ab5b367 100644 --- a/core/src/prelude.rs +++ b/core/src/prelude.rs @@ -16,12 +16,11 @@ pub use crate::{ *, }, lang::{Lang, LangHelper}, - setup_schedule_labels, - text::{LineIndex, PositionEncoding}, - systems, + setup_schedule_labels, systems, systems::prefix::{Prefix, Prefixes}, - systems::{spawn_background, spawn_or_insert}, systems::PrefixComponent, + systems::{spawn_background, spawn_or_insert}, + text::{LineIndex, PositionEncoding}, util::{ fs::*, lsp_range_to_range, offset_to_position, offsets_to_range, position_to_offset, diff --git a/core/src/systems/mod.rs b/core/src/systems/mod.rs index 07008ec26f..03c58bdab0 100644 --- a/core/src/systems/mod.rs +++ b/core/src/systems/mod.rs @@ -17,25 +17,22 @@ pub use prefix_diagnostics::{ add_missing_prefix_code_action, prefix_diagnostic_helper, prefix_diagnostics, }; mod prefix_hover; -pub use prefix_hover::{ - get_current_prefix, goto_prefix, hover_prefix, PrefixComponent, -}; +pub use prefix_hover::{get_current_prefix, goto_prefix, hover_prefix, PrefixComponent}; mod namespace_properties; +use crate::lsp_types::CompletionItemKind; pub use namespace_properties::{ unknown_property_code_action, validate_namespace_properties, ALLOW_PROPERTY_COMMAND, }; -use crate::lsp_types::CompletionItemKind; mod properties; pub use properties::{ complete_class, complete_properties, derive_ontologies, hover_class, hover_excluded_property, - hover_property, - DefinedClass, DefinedClasses, DefinedProperties, DefinedProperty, + hover_property, DefinedClass, DefinedClasses, DefinedProperties, DefinedProperty, }; mod lov; pub use lov::{ - check_added_ontology_extract, fetch_lov_properties, init_ontology_extractor, spawn_document, - configured_url, namespace_sources, populate_known_ontologies, ConfiguredOntology, FromPrefix, - NamespaceSource, PreferredPrefixes, OntologyExtractor, PrefixEntry, + check_added_ontology_extract, configured_url, fetch_lov_properties, init_ontology_extractor, + namespace_sources, populate_known_ontologies, spawn_document, ConfiguredOntology, FromPrefix, + NamespaceSource, OntologyExtractor, PreferredPrefixes, PrefixEntry, }; use tracing::instrument; @@ -97,7 +94,10 @@ pub fn spawn_background( .find(|x| x.1 .0 == url) .map(|x| x.0); if let Some(entity) = open { - tracing::debug!("{} is open in the editor, keeping the editor's content", url); + tracing::debug!( + "{} is open in the editor, keeping the editor's content", + url + ); world.entity_mut(entity).insert((extra, Background)); return entity; } diff --git a/core/src/systems/namespace_properties.rs b/core/src/systems/namespace_properties.rs index 5d7ea477c9..a56132aebf 100644 --- a/core/src/systems/namespace_properties.rs +++ b/core/src/systems/namespace_properties.rs @@ -80,7 +80,10 @@ pub fn validate_namespace_properties( ) { let closed = &config.config.local.closed_namespaces; let allowed = &config.config.local.allowed_properties; - let disabled = config.config.local.is_disabled(Disabled::NamespaceProperties); + let disabled = config + .config + .local + .is_disabled(Disabled::NamespaceProperties); for (triples, rope, item) in &query { let violations = @@ -117,7 +120,10 @@ pub fn unknown_property_code_action( ) { let closed = &config.config.local.closed_namespaces; let allowed = &config.config.local.allowed_properties; - let disabled = config.config.local.is_disabled(Disabled::NamespaceProperties); + let disabled = config + .config + .local + .is_disabled(Disabled::NamespaceProperties); for (triples, rope, position, mut req) in &mut query { let cursor = position.0; diff --git a/core/src/systems/prefix.rs b/core/src/systems/prefix.rs index 371f1461ea..5cd615d499 100644 --- a/core/src/systems/prefix.rs +++ b/core/src/systems/prefix.rs @@ -1,8 +1,8 @@ use std::{collections::HashSet, ops::Deref}; +use crate::lsp_types::Range; use bevy_ecs::prelude::*; use swls_lov::LocalPrefix; -use crate::lsp_types::Range; use tracing::instrument; use crate::{ diff --git a/core/src/systems/properties/systems.rs b/core/src/systems/properties/systems.rs index ebb21c8573..431307349f 100644 --- a/core/src/systems/properties/systems.rs +++ b/core/src/systems/properties/systems.rs @@ -109,7 +109,11 @@ pub fn complete_properties( resource: Res, config: Res, ) { - if config.config.local.is_disabled(Disabled::CompletionProperty) { + if config + .config + .local + .is_disabled(Disabled::CompletionProperty) + { return; } for (token, triple, prefixes, _this_label, types, mut request, lang) in &mut query { @@ -222,7 +226,12 @@ pub fn hover_excluded_property( config: Res, ) { let allowed = &config.config.local.allowed_properties; - if allowed.is_empty() || config.config.local.is_disabled(Disabled::HoverExcludedProperty) { + if allowed.is_empty() + || config + .config + .local + .is_disabled(Disabled::HoverExcludedProperty) + { return; } for (triple, mut request) in &mut query { diff --git a/core/src/systems/shapes/mod.rs b/core/src/systems/shapes/mod.rs index 78bd2c9f9c..b5eac5979e 100644 --- a/core/src/systems/shapes/mod.rs +++ b/core/src/systems/shapes/mod.rs @@ -23,8 +23,8 @@ use crate::{ mod data; use data::*; -pub(crate) mod model; mod describe; +pub(crate) mod model; mod template; pub use describe::{hover_shape_property, shape_property_completions}; pub use template::complete_shape_templates; diff --git a/core/src/text.rs b/core/src/text.rs index 0905d1b6e3..5acf00be13 100644 --- a/core/src/text.rs +++ b/core/src/text.rs @@ -95,7 +95,11 @@ impl LineIndex { /// Byte range `[start, end)` of `line`, including its trailing newline (if any). pub fn line_byte_range(&self, line: usize) -> Option> { let start = self.line_start(line)?; - let end = self.line_starts.get(line + 1).copied().unwrap_or(self.text.len()); + let end = self + .line_starts + .get(line + 1) + .copied() + .unwrap_or(self.text.len()); Some(start..end) } @@ -144,7 +148,11 @@ impl LineIndex { /// A `character` past the end of its line is clamped to the line's end (which /// keeps the lenient behaviour editors rely on when the cursor sits after the /// last character). Returns `None` only if the line itself is out of range. - pub fn position_to_byte(&self, position: Position, encoding: PositionEncoding) -> Option { + pub fn position_to_byte( + &self, + position: Position, + encoding: PositionEncoding, + ) -> Option { let line = position.line as usize; let line_range = self.line_byte_range(line)?; let line_text = self.text.get(line_range.clone())?; @@ -221,7 +229,10 @@ mod tests { for text in ["", "abc", "ab\ncde", "xΓ©y\nfoo", "πŸ˜€z\n€uro", "a\r\nb"] { let idx = LineIndex::new(text); // Every char boundary should round-trip byte β†’ position β†’ byte. - for (byte, _) in text.char_indices().chain(std::iter::once((text.len(), ' '))) { + for (byte, _) in text + .char_indices() + .chain(std::iter::once((text.len(), ' '))) + { let p = idx.byte_to_position(byte, U16).unwrap(); assert_eq!( idx.position_to_byte(p, U16), diff --git a/core/src/util/fs.rs b/core/src/util/fs.rs index 57b2043cc9..e5bc1e526f 100644 --- a/core/src/util/fs.rs +++ b/core/src/util/fs.rs @@ -1,7 +1,7 @@ +use crate::lsp_types::Url; use bevy_ecs::prelude::Resource; use derive_more::derive::AsRef; use std::sync::Arc; -use crate::lsp_types::Url; #[derive(Resource, Clone, AsRef, Debug)] pub struct Fs(pub Arc); diff --git a/e2e/src/lib.rs b/e2e/src/lib.rs index 097fc17c8c..01948a21a7 100644 --- a/e2e/src/lib.rs +++ b/e2e/src/lib.rs @@ -45,7 +45,10 @@ use swls_core::{ hover::{HoverRequest, Label as HoverLabel}, on_type_format::{Label as OnTypeFormatLabel, OnTypeFormatRequest}, parse::Label as ParseLabel, - rename::{PrepareRenameRequest, PrepareRename as PrepareRenameLabel, Rename as RenameLabel, RenameEdits}, + rename::{ + PrepareRename as PrepareRenameLabel, PrepareRenameRequest, Rename as RenameLabel, + RenameEdits, + }, }, lsp_types::{CodeAction, CompletionItemKind, Diagnostic, Position, Range, TextEdit, Url}, prelude::*, @@ -128,9 +131,10 @@ impl LspHarness { /// Update the source of an already-open file and re-parse. pub fn update_file(&mut self, handle: &FileHandle, new_content: &str) { - self.world - .entity_mut(handle.entity) - .insert((Source(new_content.to_string()), RopeC(LineIndex::new(new_content)))); + self.world.entity_mut(handle.entity).insert(( + Source(new_content.to_string()), + RopeC(LineIndex::new(new_content)), + )); self.world.run_schedule(ParseLabel); } @@ -247,7 +251,12 @@ impl LspHarness { /// /// Positions are 0-indexed as in the LSP spec. The character value is the index of the /// **first character of the token** being completed (consistent with the existing unit tests). - pub fn completions(&mut self, handle: &FileHandle, line: u32, character: u32) -> Vec { + pub fn completions( + &mut self, + handle: &FileHandle, + line: u32, + character: u32, + ) -> Vec { self.world.entity_mut(handle.entity).insert(( CompletionRequest(Vec::new()), PositionComponent(Position { line, character }), @@ -337,7 +346,8 @@ impl LspHarness { } /// Check whether the document currently has the `Dirty` marker (i.e. has parse errors). - pub fn is_dirty(&self, handle: &FileHandle) -> bool { self.world.entity(handle.entity).contains::() + pub fn is_dirty(&self, handle: &FileHandle) -> bool { + self.world.entity(handle.entity).contains::() } /// Current source text of a document as the server sees it. @@ -466,7 +476,10 @@ impl LspHarness { /// .contains_label("@prefix") /// .count_at_least(1); /// ``` - pub fn assert_completions<'a>(&self, completions: &'a [SimpleCompletion]) -> CompletionAssert<'a> { + pub fn assert_completions<'a>( + &self, + completions: &'a [SimpleCompletion], + ) -> CompletionAssert<'a> { CompletionAssert { completions } } diff --git a/e2e/tests/code_actions.rs b/e2e/tests/code_actions.rs index edf794e683..0fb602dcdd 100644 --- a/e2e/tests/code_actions.rs +++ b/e2e/tests/code_actions.rs @@ -172,7 +172,10 @@ fn extract_blank_node_works_in_trig() { .unwrap(); let result = apply_edits(&src, edits); assert!(result.contains("foaf:knows _:b0 ."), "got:\n{result}"); - assert!(result.contains("_:b0 foaf:name \"Alice\" ."), "got:\n{result}"); + assert!( + result.contains("_:b0 foaf:name \"Alice\" ."), + "got:\n{result}" + ); } #[test_log::test] @@ -199,7 +202,10 @@ fn extract_blank_node_works_in_sparql() { .unwrap(); let result = apply_edits(src, edits); assert!(result.contains("foaf:knows _:b0 "), "got:\n{result}"); - assert!(result.contains("_:b0 foaf:name \"Alice\" ."), "got:\n{result}"); + assert!( + result.contains("_:b0 foaf:name \"Alice\" ."), + "got:\n{result}" + ); } // ─── Inline named blank node (inverse of extract) ───────────────────────────── @@ -208,9 +214,7 @@ fn extract_blank_node_works_in_sparql() { fn inline_blank_node_offered_and_applies() { let mut h = LspHarness::new(); // A labelled blank node defined on its own line and referenced once. - let src = format!( - "{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n" - ); + let src = format!("{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n"); let file = h.open_file("file:///inline.ttl", "turtle", &src); h.drain_tasks(); @@ -243,9 +247,7 @@ fn inline_blank_node_offered_and_applies() { #[test_log::test] fn inline_offered_when_cursor_on_definition() { let mut h = LspHarness::new(); - let src = format!( - "{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n" - ); + let src = format!("{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n"); let file = h.open_file("file:///inline_def.ttl", "turtle", &src); h.drain_tasks(); @@ -292,9 +294,7 @@ fn no_inline_when_referenced_multiple_times() { #[test_log::test] fn inline_blank_node_works_in_trig() { let mut h = LspHarness::new(); - let src = format!( - "{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n" - ); + let src = format!("{PRELUDE}<#s> foaf:knows _:b0 .\n_:b0 foaf:name \"Alice\" .\n"); let file = h.open_file("file:///inline.trig", "trig", &src); h.drain_tasks(); diff --git a/e2e/tests/diagnostics.rs b/e2e/tests/diagnostics.rs index b0be508073..dcca4a4c5a 100644 --- a/e2e/tests/diagnostics.rs +++ b/e2e/tests/diagnostics.rs @@ -15,7 +15,10 @@ fn valid_turtle_has_no_dirty_marker() { foaf:name \"Alice\" ."; let file = h.open_file("file:///valid.ttl", "turtle", src); - assert!(!h.is_dirty(&file), "Valid Turtle document should not be Dirty"); + assert!( + !h.is_dirty(&file), + "Valid Turtle document should not be Dirty" + ); } #[test_log::test] @@ -25,7 +28,10 @@ fn valid_sparql_has_no_dirty_marker() { SELECT ?s WHERE { ?s a foaf:Person . }"; let file = h.open_file("file:///valid.sparql", "sparql", src); - assert!(!h.is_dirty(&file), "Valid SPARQL document should not be Dirty"); + assert!( + !h.is_dirty(&file), + "Valid SPARQL document should not be Dirty" + ); } // ─── Invalid documents ──────────────────────────────────────────────────────── diff --git a/e2e/tests/on_type_format.rs b/e2e/tests/on_type_format.rs index 33d02e1deb..fab05de0f2 100644 --- a/e2e/tests/on_type_format.rs +++ b/e2e/tests/on_type_format.rs @@ -16,7 +16,11 @@ fn typing_colon_after_known_undeclared_prefix_inserts_declaration() { .on_type_format(&file, 0, 8) .expect("typing ':' after a known prefix should insert a declaration"); - assert_eq!(edits.len(), 1, "expected a single declaration edit, got {edits:?}"); + assert_eq!( + edits.len(), + 1, + "expected a single declaration edit, got {edits:?}" + ); assert_eq!( edits[0].new_text, "@prefix foaf: .\n", "should insert the foaf prefix declaration" @@ -119,8 +123,7 @@ fn jsonld_typing_colon_in_string_adds_prefix_to_context() { #[test_log::test] fn jsonld_typing_colon_for_declared_prefix_does_nothing() { let mut h = LspHarness::new(); - let src = - r#"{"@context": {"foaf": "http://xmlns.com/foaf/0.1/"}, "foaf:knows": "x"}"#; + let src = r#"{"@context": {"foaf": "http://xmlns.com/foaf/0.1/"}, "foaf:knows": "x"}"#; let file = h.open_file("file:///otf_decl.jsonld", "jsonld", src); h.drain_tasks(); diff --git a/e2e/tests/prefix_diagnostics.rs b/e2e/tests/prefix_diagnostics.rs index 2bc50a72f4..f7fbdb91bf 100644 --- a/e2e/tests/prefix_diagnostics.rs +++ b/e2e/tests/prefix_diagnostics.rs @@ -47,13 +47,11 @@ fn undefined_prefix_diagnostic_spans_the_token() { let diags = h.run_diagnostics(); - let error = diags - .iter() - .find(|(url, d)| { - url.as_str() == file.url - && d.severity == Some(DiagnosticSeverity::ERROR) - && d.message.contains("\"ex\"") - }); + let error = diags.iter().find(|(url, d)| { + url.as_str() == file.url + && d.severity == Some(DiagnosticSeverity::ERROR) + && d.message.contains("\"ex\"") + }); assert!( error.is_some(), @@ -133,8 +131,7 @@ fn undefined_prefix_quickfix_links_all_occurrence_diagnostics() { assert!( linked .iter() - .all(|d| d.severity == Some(DiagnosticSeverity::ERROR) - && d.message.contains("\"ex\"")), + .all(|d| d.severity == Some(DiagnosticSeverity::ERROR) && d.message.contains("\"ex\"")), "linked diagnostics should be the undefined-prefix errors, got: {:?}", linked.iter().map(|d| &d.message).collect::>() ); @@ -360,7 +357,10 @@ fn add_missing_prefix_code_action_inserts_at_file_top() { .and_then(|c| c.values().next()) .expect("code action should have text edits"); - assert!(!edits.is_empty(), "code action should have at least one edit"); + assert!( + !edits.is_empty(), + "code action should have at least one edit" + ); // The insert position should be at the top (line 0, char 0) let edit = &edits[0]; @@ -399,9 +399,7 @@ fn jsonld_prefix_warnings(src: &str, url: &str) -> Vec { h.drain_tasks(); h.run_diagnostics() .into_iter() - .filter(|(u, d)| { - u.as_str() == file.url && d.severity == Some(DiagnosticSeverity::WARNING) - }) + .filter(|(u, d)| u.as_str() == file.url && d.severity == Some(DiagnosticSeverity::WARNING)) .map(|(_, d)| d.message) .collect() } @@ -581,7 +579,10 @@ fn add_missing_prefix_code_action_disabled_by_config() { let actions = h.code_actions(&file); - let add_foaf: Vec<_> = actions.iter().filter(|a| a.title.contains("foaf")).collect(); + let add_foaf: Vec<_> = actions + .iter() + .filter(|a| a.title.contains("foaf")) + .collect(); assert!( add_foaf.is_empty(), diff --git a/e2e/tests/rename.rs b/e2e/tests/rename.rs index 097f85560b..ce6495ce46 100644 --- a/e2e/tests/rename.rs +++ b/e2e/tests/rename.rs @@ -27,7 +27,9 @@ fn prepare_rename_turtle_iri_strips_angle_brackets() { let src = "@prefix ex: .\nex:s ex:o ."; let file = h.open_file("file:///iri_rename.ttl", "turtle", src); - let result = h.prepare_rename(&file, 1, 5).expect("rename should be available on IRI token"); + let result = h + .prepare_rename(&file, 1, 5) + .expect("rename should be available on IRI token"); assert_eq!( result.placeholder, "http://example.org/pred", "placeholder should strip angle brackets" @@ -257,7 +259,8 @@ fn prepare_rename_jsonld_iri_strips_double_quotes() { // Minimal JSON-LD document with a quoted IRI as @id value // The term span covers `"http://example.org/subject"` (with quotes). // The placeholder shown to the user should strip the quotes. - let src = r#"{"@id": "http://example.org/subject", "http://example.org/pred": {"@value": "hello"}}"#; + let src = + r#"{"@id": "http://example.org/subject", "http://example.org/pred": {"@value": "hello"}}"#; let file = h.open_file("file:///id_rename.jsonld", "jsonld", src); h.drain_tasks(); @@ -285,7 +288,8 @@ fn prepare_rename_jsonld_iri_strips_double_quotes() { #[test_log::test] fn rename_jsonld_iri_wraps_new_name_in_quotes() { let mut h = LspHarness::new(); - let src = r#"{"@id": "http://example.org/subject", "http://example.org/pred": {"@value": "hello"}}"#; + let src = + r#"{"@id": "http://example.org/subject", "http://example.org/pred": {"@value": "hello"}}"#; let file = h.open_file("file:///id_rewrap.jsonld", "jsonld", src); h.drain_tasks(); diff --git a/e2e/tests/settings.rs b/e2e/tests/settings.rs index 352ca6ee34..8e3babd0a3 100644 --- a/e2e/tests/settings.rs +++ b/e2e/tests/settings.rs @@ -112,8 +112,7 @@ fn allow_listed_property_does_not_warn() { let mut h = LspHarness::new(); h.set_config(|c| { c.closed_namespaces.insert(CFG_NS.to_string()); - c.allowed_properties - .insert(format!("{CFG_NS}unknown")); + c.allowed_properties.insert(format!("{CFG_NS}unknown")); }); h.open_linked_file("file:///cfg-onto2.ttl", "turtle", CFG_ONTO_TTL); @@ -187,7 +186,8 @@ fn unknown_property_offers_allow_quick_fix() { .and_then(|c| c.arguments.as_ref()) .expect("command should carry arguments"); assert!( - args.iter().any(|v| v.as_str() == Some(&format!("{CFG_NS}unknown"))), + args.iter() + .any(|v| v.as_str() == Some(&format!("{CFG_NS}unknown"))), "quick-fix should target cfg:unknown, got: {args:?}" ); } @@ -219,8 +219,7 @@ fn hover_on_allow_listed_property_explains_exclusion() { let mut h = LspHarness::new(); h.set_config(|c| { c.closed_namespaces.insert(CFG_NS.to_string()); - c.allowed_properties - .insert(format!("{CFG_NS}unknown")); + c.allowed_properties.insert(format!("{CFG_NS}unknown")); }); h.open_linked_file("file:///cfg-onto5.ttl", "turtle", CFG_ONTO_TTL); @@ -278,7 +277,11 @@ fn syntax_diagnostics_disabled_by_config() { }); // Missing closing `.` β€” a syntax error. - let file = h.open_file("file:///syntax_disabled.ttl", "turtle", "<> a "); + let file = h.open_file( + "file:///syntax_disabled.ttl", + "turtle", + "<> a ", + ); let diags = h.run_diagnostics(); let syntax_errors: Vec<_> = diags @@ -289,6 +292,9 @@ fn syntax_diagnostics_disabled_by_config() { assert!( syntax_errors.is_empty(), "syntax diagnostics should be silenced when disabled, got: {:?}", - syntax_errors.iter().map(|(_, d)| &d.message).collect::>() + syntax_errors + .iter() + .map(|(_, d)| &d.message) + .collect::>() ); } diff --git a/e2e/tests/turtle_completion.rs b/e2e/tests/turtle_completion.rs index cdc099051a..5e9a191e4c 100644 --- a/e2e/tests/turtle_completion.rs +++ b/e2e/tests/turtle_completion.rs @@ -309,7 +309,8 @@ fn completion_prefix_disabled_by_config() { h.drain_tasks(); let completions = h.completions(&file, 1, 0); - h.assert_completions(&completions).does_not_contain_label("foaf"); + h.assert_completions(&completions) + .does_not_contain_label("foaf"); } #[test_log::test] diff --git a/lang-jsonld/src/ecs/completion.rs b/lang-jsonld/src/ecs/completion.rs index eb28e02801..d442eea783 100644 --- a/lang-jsonld/src/ecs/completion.rs +++ b/lang-jsonld/src/ecs/completion.rs @@ -362,7 +362,11 @@ pub fn jsonld_property_completion( registry: Res, config: Res, ) { - if config.config.local.is_disabled(Disabled::CompletionProperty) { + if config + .config + .local + .is_disabled(Disabled::CompletionProperty) + { return; } for (token, triple, types, active_ctx, prefixes, mut request) in &mut query { @@ -462,9 +466,7 @@ mod tests { // spawned task), so drive those tasks to completion before querying the // cursor's triple. let client = world.resource::().clone(); - futures::executor::block_on( - client.await_futures(|| world.run_schedule(swls_core::Tasks)), - ); + futures::executor::block_on(client.await_futures(|| world.run_schedule(swls_core::Tasks))); // Verify that a TripleComponent is set with Predicate target when the // cursor is inside the "foaf:name" key (line 3, char 3 β‰ˆ inside the key). diff --git a/lang-jsonld/src/ecs/mod.rs b/lang-jsonld/src/ecs/mod.rs index f79685e0c8..d3e8bdd666 100644 --- a/lang-jsonld/src/ecs/mod.rs +++ b/lang-jsonld/src/ecs/mod.rs @@ -587,7 +587,10 @@ mod id_highlight { world.entity_mut(entity).insert(HighlightRequest(vec![])); world.run_schedule(SemanticLabel); - let ttc = world.entity(entity).get::().expect("ttc"); + let ttc = world + .entity(entity) + .get::() + .expect("ttc"); let mut ts: Vec> = vec![None; src.len()]; for s in &ttc.0 { for j in s.span().clone() { @@ -654,7 +657,10 @@ mod id_highlight { world.entity_mut(entity).insert(HighlightRequest(vec![])); world.run_schedule(SemanticLabel); - let ttc = world.entity(entity).get::().expect("ttc"); + let ttc = world + .entity(entity) + .get::() + .expect("ttc"); let mut ts: Vec> = vec![None; src.len()]; for s in &ttc.0 { for j in s.span().clone() { @@ -665,7 +671,9 @@ mod id_highlight { } // Assert every byte of `needle`'s single occurrence has type `expected`. let all = |needle: &str, expected: &str| { - let q = src.find(needle).unwrap_or_else(|| panic!("missing {needle:?}")); + let q = src + .find(needle) + .unwrap_or_else(|| panic!("missing {needle:?}")); for b in q..q + needle.len() { assert_eq!( ts[b].as_ref().map(|t| t.as_str()), diff --git a/lang-jsonld/src/lib.rs b/lang-jsonld/src/lib.rs index ccfebae6dd..7695547524 100644 --- a/lang-jsonld/src/lib.rs +++ b/lang-jsonld/src/lib.rs @@ -53,7 +53,8 @@ impl LangHelper for JsonLdHelper { /// A full IRI is a plain JSON string value. fn write_iri(&self, prefixes: &Prefixes, iri: &str) -> String { - self.shorten(prefixes, iri).unwrap_or_else(|| iri.to_string()) + self.shorten(prefixes, iri) + .unwrap_or_else(|| iri.to_string()) } fn keyword(&self) -> &[&'static str] { @@ -340,7 +341,11 @@ fn goto_cjs( ) { use swls_core::lsp_types::{Location, Range}; - if config.config.local.is_disabled(Disabled::GotoDefinitionComponentsJs) { + if config + .config + .local + .is_disabled(Disabled::GotoDefinitionComponentsJs) + { return; } diff --git a/lang-n3/src/ecs/mod.rs b/lang-n3/src/ecs/mod.rs index cece8e6cc2..dfaf7a7b2d 100644 --- a/lang-n3/src/ecs/mod.rs +++ b/lang-n3/src/ecs/mod.rs @@ -54,9 +54,8 @@ fn collect_errors( match child { NodeOrToken::Node(n) => { if n.kind() == SyntaxKind::Error { - let range = rdf_parsers::effective_error_span::< - rdf_parsers::n3::parser::Lang, - >(&n); + let range = + rdf_parsers::effective_error_span::(&n); let msg = n .parent() .map(|p| format!("Expected: {:?}", p.kind())) diff --git a/lang-rdf-base/src/code_actions.rs b/lang-rdf-base/src/code_actions.rs index 9874a7c67d..b16faf2f16 100644 --- a/lang-rdf-base/src/code_actions.rs +++ b/lang-rdf-base/src/code_actions.rs @@ -96,7 +96,11 @@ pub fn extract_blank_node( )>, config: Res, ) { - if config.config.local.is_disabled(Disabled::CodeActionBlankNodeRefactor) { + if config + .config + .local + .is_disabled(Disabled::CodeActionBlankNodeRefactor) + { return; } for (element, source, rope, label, position, lang, mut req) in &mut query { @@ -183,11 +187,7 @@ pub fn extract_blank_node( /// returning its label and span. Searches subjects, predicates and objects /// recursively (into nested `[ … ]` and collections). fn find_named_at(turtle: &Turtle, offset: usize) -> Option<(String, StdRange)> { - fn walk( - term: &Spanned, - offset: usize, - best: &mut Option<(String, StdRange)>, - ) { + fn walk(term: &Spanned, offset: usize, best: &mut Option<(String, StdRange)>) { let span = term.span(); if offset < span.start || offset > span.end { return; @@ -278,7 +278,11 @@ pub fn inline_blank_node( )>, config: Res, ) { - if config.config.local.is_disabled(Disabled::CodeActionBlankNodeRefactor) { + if config + .config + .local + .is_disabled(Disabled::CodeActionBlankNodeRefactor) + { return; } for (element, source, rope, label, position, lang, mut req) in &mut query { diff --git a/lang-rdf-base/src/rename.rs b/lang-rdf-base/src/rename.rs index 712b779590..5749df5634 100644 --- a/lang-rdf-base/src/rename.rs +++ b/lang-rdf-base/src/rename.rs @@ -132,7 +132,8 @@ fn find_renameable_with( let mut best: Option<(StdRange, RenameKey, String)> = None; walk_terms(turtle, |term| { let span = term.span(); - let contains = span.start <= offset && (offset < span.end || (inclusive && offset == span.end)); + let contains = + span.start <= offset && (offset < span.end || (inclusive && offset == span.end)); if !contains { return; } diff --git a/lang-sparql/src/ecs/mod.rs b/lang-sparql/src/ecs/mod.rs index 0be113d251..c4d9ccd890 100644 --- a/lang-sparql/src/ecs/mod.rs +++ b/lang-sparql/src/ecs/mod.rs @@ -11,11 +11,7 @@ use sophia_api::{ quad::Quad as _, term::{Term as _, TermKind}, }; -use swls_core::{ - components::*, - lsp_types::CompletionItemKind, - prelude::*, -}; +use swls_core::{components::*, lsp_types::CompletionItemKind, prelude::*}; use swls_lang_rdf_base::traits::{NamedNodeExt, TurtleExt}; use crate::Sparql; @@ -302,7 +298,13 @@ mod format_tests { cfg.config.local.format.sparql = None; world.insert_resource(cfg); - let entity = create_file(&mut world, src, "http://example.com/update.ru", "sparql", Open); + let entity = create_file( + &mut world, + src, + "http://example.com/update.ru", + "sparql", + Open, + ); world.run_schedule(ParseLabel); let dirty = world.entity(entity).contains::(); diff --git a/lang-trig/src/ecs/mod.rs b/lang-trig/src/ecs/mod.rs index 8a31ad695b..2e847bb0bd 100644 --- a/lang-trig/src/ecs/mod.rs +++ b/lang-trig/src/ecs/mod.rs @@ -206,7 +206,10 @@ mod tests { #[test] fn trig_formatting_on_by_default() { - assert_eq!(format_with(None).as_deref(), Some(" ;\n .\n")); + assert_eq!( + format_with(None).as_deref(), + Some(" ;\n .\n") + ); } #[test] diff --git a/lang-turtle/src/ecs/code_action.rs b/lang-turtle/src/ecs/code_action.rs index 427ac9ab06..c2270e4707 100644 --- a/lang-turtle/src/ecs/code_action.rs +++ b/lang-turtle/src/ecs/code_action.rs @@ -15,7 +15,11 @@ pub fn organize_imports( mut query: Query<(&Element, &RopeC, &Label, &mut CodeActionRequest), With>, config: Res, ) { - if config.config.local.is_disabled(Disabled::CodeActionOrganizeImports) { + if config + .config + .local + .is_disabled(Disabled::CodeActionOrganizeImports) + { return; } for (turtle, rope, label, mut req) in &mut query { diff --git a/lang-turtle/src/ecs/completion.rs b/lang-turtle/src/ecs/completion.rs index 28295600b0..c32f3eac31 100644 --- a/lang-turtle/src/ecs/completion.rs +++ b/lang-turtle/src/ecs/completion.rs @@ -13,12 +13,7 @@ use swls_lang_rdf_base::traits::{NamedNodeExt, TurtleExt}; pub fn subject_completion( mut query: Query< - ( - &TokenComponent, - &Element, - &Prefixes, - &mut CompletionRequest, - ), + (&TokenComponent, &Element, &Prefixes, &mut CompletionRequest), With, >, triples: Query<(&Triples, &Label), With>, diff --git a/lang-turtle/src/ecs/mod.rs b/lang-turtle/src/ecs/mod.rs index c56e177a82..4e6115a071 100644 --- a/lang-turtle/src/ecs/mod.rs +++ b/lang-turtle/src/ecs/mod.rs @@ -185,7 +185,8 @@ mod prefix_datatype_tests { #[test] fn datatype_prefix_counts_as_used() { - let src = "@prefix xsd: .\n

\"5\"^^xsd:integer .\n"; + let src = + "@prefix xsd: .\n

\"5\"^^xsd:integer .\n"; let msgs = run(src, &["xsd"], true); assert!( !msgs.iter().any(|m| m.contains("never used")), diff --git a/swls/src/server.rs b/swls/src/server.rs index f7057f2ab6..c784ac8afb 100644 --- a/swls/src/server.rs +++ b/swls/src/server.rs @@ -24,11 +24,7 @@ pub struct LspBackend { } impl LspBackend { - pub fn new( - sender: CommandSender, - client: TowerClient, - tokens: Vec, - ) -> Self { + pub fn new(sender: CommandSender, client: TowerClient, tokens: Vec) -> Self { Self { backend: Backend::new(sender, client, tokens), } @@ -88,10 +84,7 @@ impl LanguageServer for LspBackend { lift(self.backend.hover(params).await) } - async fn formatting( - &self, - params: DocumentFormattingParams, - ) -> Result>> { + async fn formatting(&self, params: DocumentFormattingParams) -> Result>> { lift(self.backend.formatting(params).await) } From 3f0c4577fadf553a957872688cbbf5b3c40768fd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:43:14 +0000 Subject: [PATCH 03/10] chore: ignore the formatting commit in git blame --- .git-blame-ignore-revs | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .git-blame-ignore-revs 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 From 2e337e67f248c0f3372b27a5a09efd9de1f1ac83 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 14:52:37 +0000 Subject: [PATCH 04/10] chore: fix clippy warnings and configure workspace lints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Makes `cargo clippy --workspace --all-targets -- -D warnings` pass. - Workspace lints (`[workspace.lints.clippy]`, inherited by every crate): `type_complexity` and `too_many_arguments` are allowed, because Bevy systems take their data as parameters and nested `Query` types. - `cargo clippy --fix` for the mechanical lints (needless borrows, redundant closures and returns, `'static` on constants, …). - By hand: - `Option::is_none_or` (Rust 1.82) replaced in components-rs, whose MSRV is 1.75; - `try_next` (deprecated) replaced by `try_recv` on the command and diagnostic channels; - `MyQuad::into_oxi(_graph)` return `Option` instead of `Result<_, ()>`; - `PartialOrd` for `MyTerm` delegates to `Ord`; - `assert!(false, …)` β†’ `panic!` in the conformance tests; - a few `sort_by_key`, `while let`, `is_err()` and merged `if` branches; - `TestFs: Default`; - kept the needed clone in the config loaders (clippy's suggestion does not compile, the value moves into a spawned future); - pinned a lifetime in `prefix_completion_helper` that the elided form could not express. - `wrong_self_convention` is allowed on the two public `into_triples` trait methods rather than renaming them across crates. --- Cargo.toml | 5 + components-rs/Cargo.toml | 3 + components-rs/src/components/registry.rs | 6 + components-rs/src/config/registry.rs | 6 + components-rs/src/context/expand.rs | 4 +- components-rs/src/discovery/node_modules.rs | 6 +- conformance/Cargo.toml | 3 + conformance/build.rs | 3 + conformance/src/lib.rs | 4 +- conformance/src/main.rs | 2 +- core/Cargo.toml | 3 + core/src/backend.rs | 9 +- core/src/feature/completion.rs | 13 +- core/src/feature/diagnostics.rs | 2 +- core/src/feature/goto_definition.rs | 8 +- core/src/lang.rs | 25 ++- core/src/systems/links.rs | 6 +- core/src/systems/lov/extractor.rs | 12 +- core/src/systems/lov/fetch.rs | 14 +- core/src/systems/mod.rs | 6 +- core/src/systems/prefix.rs | 167 ++++++++++---------- core/src/systems/prefix_diagnostics.rs | 2 +- core/src/systems/prefix_hover.rs | 4 +- core/src/systems/properties/query.rs | 146 ++++++++--------- core/src/systems/properties/systems.rs | 18 +-- core/src/systems/properties/types.rs | 4 +- core/src/systems/shapes/data.rs | 20 +-- core/src/systems/shapes/mod.rs | 9 +- core/src/systems/shapes/model.rs | 2 +- core/src/util/triple.rs | 40 +++-- e2e/Cargo.toml | 3 + lang-jsonld/Cargo.toml | 3 + lang-jsonld/src/ecs/completion.rs | 18 +-- lang-jsonld/src/ecs/mod.rs | 10 +- lang-jsonld/src/lib.rs | 24 ++- lang-n3/Cargo.toml | 3 + lang-n3/src/ecs/mod.rs | 62 ++++---- lang-rdf-base/Cargo.toml | 3 + lang-rdf-base/src/lib.rs | 4 +- lang-rdf-base/src/traits.rs | 2 + lang-rdf-base/src/triples.rs | 2 + lang-sparql/Cargo.toml | 3 + lang-sparql/src/ecs/mod.rs | 2 +- lang-trig/Cargo.toml | 3 + lang-turtle/Cargo.toml | 3 + lang-turtle/src/config.rs | 8 +- lang-turtle/src/ecs/completion.rs | 2 +- lang-turtle/src/ecs/mod.rs | 2 +- lang-turtle/src/prefix.rs | 10 +- lov/Cargo.toml | 3 + lov/src/lib.rs | 2 +- lov/src/min_prefixes.rs | 2 +- swls/Cargo.toml | 3 + swls/src/client.rs | 18 ++- swls/src/timings.rs | 6 + test-utils/Cargo.toml | 3 + test-utils/src/lib.rs | 20 ++- 57 files changed, 411 insertions(+), 365 deletions(-) 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 792727d634..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 { diff --git a/components-rs/src/config/registry.rs b/components-rs/src/config/registry.rs index f3a85df82c..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 { diff --git a/components-rs/src/context/expand.rs b/components-rs/src/context/expand.rs index dfae5ddeec..49dfd9419a 100644 --- a/components-rs/src/context/expand.rs +++ b/components-rs/src/context/expand.rs @@ -202,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)); } } @@ -255,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 diff --git a/components-rs/src/discovery/node_modules.rs b/components-rs/src/discovery/node_modules.rs index 2dda257231..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; } 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 60142bac87..46e005dbcc 100644 --- a/core/src/backend.rs +++ b/core/src/backend.rs @@ -76,7 +76,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)); }; }); @@ -101,7 +101,7 @@ impl Backend { commands.push(move |world: &mut World| { 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); }; }); @@ -293,7 +293,6 @@ impl Backend { config.workspaces.extend(added); }) .await; - () } #[instrument(skip(self, params), fields(uri = %params.text_document.uri.as_str()))] @@ -453,7 +452,7 @@ impl Backend { .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, @@ -487,7 +486,7 @@ 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))] diff --git a/core/src/feature/completion.rs b/core/src/feature/completion.rs index c7a8e0ad74..0816248ae3 100644 --- a/core/src/feature/completion.rs +++ b/core/src/feature/completion.rs @@ -128,8 +128,8 @@ impl SimpleCompletion { } } -impl Into for SimpleCompletion { - fn into(self) -> CompletionItem { +impl From for CompletionItem { + fn from(val: SimpleCompletion) -> Self { let SimpleCompletion { _is_snippet: is_snippet, _filter_text: filter_text, @@ -140,12 +140,9 @@ impl Into for SimpleCompletion { kind, edits, _commit_char: commit_char, - } = self; + } = val; - let text_edit = edits - .iter() - .next() - .map(|x| CompletionTextEdit::Edit(x.clone())); + let text_edit = edits.first().map(|x| CompletionTextEdit::Edit(x.clone())); let additional_text_edits = edits.into_iter().skip(1).collect(); @@ -165,7 +162,7 @@ impl Into for SimpleCompletion { }), text_edit, additional_text_edits: Some(additional_text_edits), - commit_characters: commit_char.map(|x| vec![String::from(x)]), + commit_characters: commit_char.map(|x| vec![x]), ..Default::default() } } diff --git a/core/src/feature/diagnostics.rs b/core/src/feature/diagnostics.rs index f594733c6b..90c2fa449b 100644 --- a/core/src/feature/diagnostics.rs +++ b/core/src/feature/diagnostics.rs @@ -132,7 +132,7 @@ pub fn publish_diagnostics( .0 .iter() .cloned() - .map(|x| Into::::into(x)) + .map(Into::::into) .flat_map(|item| { let (span, message) = (item.range, item.msg); let start_position = offset_to_position(span.start, &rope.0)?; diff --git a/core/src/feature/goto_definition.rs b/core/src/feature/goto_definition.rs index 5bd0ed55d8..6142a8ed32 100644 --- a/core/src/feature/goto_definition.rs +++ b/core/src/feature/goto_definition.rs @@ -92,23 +92,23 @@ mod system { let subs: HashSet<_> = triples .iter() .map(|x| x.s()) - .filter(|x| &x.value == &term.value) + .filter(|x| x.value == term.value) .collect(); req.0.extend( subs.into_iter() - .flat_map(|t| token_to_location(&t.span, label, &rope)), + .flat_map(|t| token_to_location(&t.span, label, rope)), ); } } else if target == TermKind::BlankNode { let subs: HashSet<_> = triples .iter() .map(|x| x.s()) - .filter(|x| &x.value == &term.value) + .filter(|x| x.value == term.value) .collect(); req.0.extend( subs.into_iter() - .flat_map(|t| token_to_location(&t.span, label, &rope)), + .flat_map(|t| token_to_location(&t.span, label, rope)), ); } } diff --git a/core/src/lang.rs b/core/src/lang.rs index 96e27bbb13..aa61ea3f90 100644 --- a/core/src/lang.rs +++ b/core/src/lang.rs @@ -9,10 +9,7 @@ pub fn head() -> crate::lsp_types::Range { line: 0, character: 0, }; - crate::lsp_types::Range { - end: start.clone(), - start, - } + crate::lsp_types::Range { end: start, start } } pub trait Lang: 'static { @@ -66,7 +63,7 @@ pub trait LangHelper: std::fmt::Debug { inp } fn quote(&self, inp: &str) -> String { - format!("{}", inp) + inp.to_string() } /// Return the source keyword used to introduce a prefix declaration /// (used only for display / span-finding purposes). @@ -194,9 +191,7 @@ pub trait LangHelper: std::fmt::Debug { /// - contains `:` but no `://` β†’ prefixed name (e.g. `ex:foo`), keep as-is /// - otherwise β†’ bare label, wrap in `< >` to be safe fn rename_wrap(&self, new_text: &str) -> String { - if new_text.starts_with('<') && new_text.ends_with('>') { - new_text.to_string() - } else if new_text.starts_with("_:") { + if (new_text.starts_with('<') && new_text.ends_with('>')) || new_text.starts_with("_:") { new_text.to_string() } else if new_text.contains("://") { format!("<{}>", new_text) @@ -251,11 +246,10 @@ pub trait LangHelper: std::fmt::Debug { types: Vec>, ) -> Option { let (label, position) = if let Some(lt) = last_type { - if let Some(pos) = offset_to_position(lt.end, &rope) { + { + let pos = offset_to_position(lt.end, rope)?; let label = format!(", {}", types.join(", ")); (label, pos) - } else { - return None; } } else { let offset = if rope.char_at_byte(subject.start) == Some('[') { @@ -264,15 +258,14 @@ pub trait LangHelper: std::fmt::Debug { subject.end }; - if let Some(pos) = offset_to_position(offset, &rope) { + { + let pos = offset_to_position(offset, rope)?; let label = format!(" a {};", types.join(", ")); (label, pos) - } else { - return None; } }; - return Some(crate::lsp_types::InlayHint { + Some(crate::lsp_types::InlayHint { position, label: crate::lsp_types::InlayHintLabel::String(label), kind: None, @@ -281,6 +274,6 @@ pub trait LangHelper: std::fmt::Debug { padding_left: None, padding_right: None, data: None, - }); + }) } } diff --git a/core/src/systems/links.rs b/core/src/systems/links.rs index c2f1b11bfe..bc08414dff 100644 --- a/core/src/systems/links.rs +++ b/core/src/systems/links.rs @@ -21,7 +21,7 @@ pub fn derive_prefix_links( mut commands: Commands, fs: Res, ) { - const SOURCE: &'static str = "prefix import"; + const SOURCE: &str = "prefix import"; let refresh_all = !new_configured.is_empty(); for (e, prefixes, mut links) in &mut query { if !refresh_all && !prefixes.is_changed() { @@ -29,7 +29,7 @@ pub fn derive_prefix_links( } let mut new_links = Vec::new(); for u in prefixes.0.iter() { - let sources = namespace_sources(&fs, u.url.as_str(), &u.prefix, &preferred, &locals); + let sources = namespace_sources(&fs, u.url.as_str(), &u.prefix, &preferred, locals); if sources.is_empty() { new_links.push((u.url.clone(), SOURCE)); } @@ -58,7 +58,7 @@ pub fn derive_owl_imports_links( mut commands: Commands, fs: Res, ) { - const SOURCE: &'static str = "owl:imports"; + const SOURCE: &str = "owl:imports"; for (e, label, triples, mut links) in &mut query { if let Some(links) = links.as_mut() { links.retain(|e| e.1 != SOURCE); diff --git a/core/src/systems/lov/extractor.rs b/core/src/systems/lov/extractor.rs index e7afd177f7..480b6e0145 100644 --- a/core/src/systems/lov/extractor.rs +++ b/core/src/systems/lov/extractor.rs @@ -95,6 +95,12 @@ impl TermMatcher for LocalMatcher<'_> { } } +impl Default for OntologyExtractor { + fn default() -> Self { + Self::new() + } +} + impl OntologyExtractor { pub fn new() -> Self { Self { @@ -110,18 +116,18 @@ impl OntologyExtractor { } } - pub fn properties<'a>(&'a self) -> &'a [MyTerm<'static>] { + pub fn properties(&self) -> &[MyTerm<'static>] { &self.properties[..] } - pub fn classes<'a>(&'a self) -> &'a [MyTerm<'static>] { + pub fn classes(&self) -> &[MyTerm<'static>] { &self.classes[..] } fn extract_step(quads: &Vec>, items: &mut Vec>) -> bool { let new_items: Vec<_> = quads .quads_matching( - LocalMatcher { properties: &items }, + LocalMatcher { properties: items }, [rdfs::subClassOf], &items[..], Any, diff --git a/core/src/systems/lov/fetch.rs b/core/src/systems/lov/fetch.rs index e316556cc1..04ef3e216a 100644 --- a/core/src/systems/lov/fetch.rs +++ b/core/src/systems/lov/fetch.rs @@ -87,13 +87,9 @@ pub fn fetch_lov_properties( for prefs in prefixes { for prefix in prefs.0.iter() { - for source in namespace_sources( - &fs, - prefix.url.as_str(), - &prefix.prefix, - &preferred, - &locals, - ) { + for source in + namespace_sources(&fs, prefix.url.as_str(), &prefix.prefix, &preferred, locals) + { if !loaded.insert(source.url.to_string()) { continue; } @@ -147,7 +143,7 @@ pub fn spawn_document( content: String, language: Option, sender: &Sender, - extra: impl FnOnce(Entity, &mut World) -> () + Send + Sync + 'static, + extra: impl FnOnce(Entity, &mut World) + Send + Sync + 'static, ) { let mut command_queue = CommandQueue::default(); let item = TextDocumentItem { @@ -226,7 +222,7 @@ pub(super) async fn fetch_lov_body( // Fall back to the LOV API: fetch vocabulary info to find the latest file URL. if namespace.ends_with('#') || namespace.ends_with('/') { - if let Some(url) = extract_file_url(&prefix, &c).await { + if let Some(url) = extract_file_url(prefix, &c).await { match c.fetch(&url, &std::collections::HashMap::new()).await { Ok(resp) if resp.status == 200 => return Some(resp.body), Ok(resp) => { diff --git a/core/src/systems/mod.rs b/core/src/systems/mod.rs index 03c58bdab0..d936d6259b 100644 --- a/core/src/systems/mod.rs +++ b/core/src/systems/mod.rs @@ -45,7 +45,7 @@ pub fn spawn_or_insert( move |world: &mut World| { let out = if let Some(entity) = world .query::<(Entity, &Label)>() - .iter(&world) + .iter(world) .find(|x| x.1 .0 == url) .map(|x| x.0) { @@ -106,7 +106,7 @@ pub fn spawn_background( } pub fn handle_tasks(mut commands: Commands, mut receiver: ResMut) { - while let Ok(Some(mut com)) = receiver.0.try_next() { + while let Ok(mut com) = receiver.0.try_recv() { commands.append(&mut com); } } @@ -140,7 +140,7 @@ pub fn keyword_complete( CompletionItemKind::KEYWORD, kwd.to_string(), crate::lsp_types::TextEdit { - range: range.clone(), + range, new_text: kwd.to_string(), }, ); diff --git a/core/src/systems/prefix.rs b/core/src/systems/prefix.rs index 5cd615d499..a345004212 100644 --- a/core/src/systems/prefix.rs +++ b/core/src/systems/prefix.rs @@ -11,7 +11,7 @@ use crate::{ systems::PrefixEntry, }; -pub const PREFIX_CC: &'static str = include_str!("./prefix_cc.txt"); +pub const PREFIX_CC: &str = include_str!("./prefix_cc.txt"); /// One defined prefix, maps prefix name to URL. #[derive(Debug, Clone)] @@ -111,81 +111,6 @@ pub fn is_local_name(local: &str) -> bool { !local.ends_with('.') } -#[cfg(test)] -mod shorten_tests { - use super::*; - - fn prefixes(decls: &[(&str, &str)]) -> Prefixes { - Prefixes( - decls - .iter() - .map(|(p, u)| Prefix { - prefix: p.to_string(), - url: crate::lsp_types::Url::parse(u).unwrap(), - }) - .collect(), - crate::lsp_types::Url::parse("file:///doc.ttl").unwrap(), - ) - } - - #[test] - fn local_names() { - for ok in [ - "", - "name", - "Name_1", - "a.b", - "1abc", - "a:b", - "caf\u{e9}", - "a%20b", - "a-b", - ] { - assert!(is_local_name(ok), "{ok:?} should be valid"); - } - for bad in [ - "a/b", "a#b", "a.", "-a", ".a", "a b", "a?b", "a%2", "a~b", "a,b", - ] { - assert!(!is_local_name(bad), "{bad:?} should be invalid"); - } - } - - #[test] - fn shorten_only_to_valid_prefixed_names() { - let p = prefixes(&[("rml", "http://w3id.org/rml/")]); - assert_eq!( - p.shorten("http://w3id.org/rml/TriplesMap").as_deref(), - Some("rml:TriplesMap") - ); - assert_eq!(p.shorten("http://w3id.org/rml/shapes/X"), None); - assert_eq!( - p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(), - Some("rml:shapes/X") - ); - assert_eq!(p.shorten("http://other.test/x"), None); - } - - #[test] - fn longest_namespace_wins() { - let p = prefixes(&[ - ("rml", "http://w3id.org/rml/"), - ("rmlsh", "http://w3id.org/rml/shapes/"), - ]); - assert_eq!( - p.shorten("http://w3id.org/rml/shapes/X").as_deref(), - Some("rmlsh:X") - ); - assert_eq!( - p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(), - Some("rmlsh:X") - ); - assert_eq!( - p.shorten("http://w3id.org/rml/source").as_deref(), - Some("rml:source") - ); - } -} - enum PrefixLike<'a> { Prefix(&'a Prefix), Local(&'a LocalPrefix), @@ -215,7 +140,7 @@ impl PrefixLike<'_> { let nt = format!("{}:$0", name); let mut completion = SimpleCompletion::new( CompletionItemKind::MODULE, - format!("{}", name), + name.to_string(), crate::lsp_types::TextEdit { new_text: lang.quote(&nt), range, @@ -257,7 +182,7 @@ impl PrefixLike<'_> { pub fn prefix_completion_helper<'a>( word: &TokenComponent, - prefixes: &Prefixes, + prefixes: &'a Prefixes, completions: &mut Vec, mut extra_edits: impl FnMut(&str, &str) -> Option>, lovs: impl Iterator, @@ -269,8 +194,8 @@ pub fn prefix_completion_helper<'a>( tracing::debug!("completion helper {:?}", word); completions.extend( - lovs.map(|x| PrefixLike::Local(&x)) - .chain(prefix_cc.map(|x| PrefixLike::Entry(x))) + lovs.map(PrefixLike::Local) + .chain(prefix_cc.map(PrefixLike::Entry)) .chain(prefixes.iter().map(PrefixLike::Prefix)) .filter(|p| p.name().starts_with(text)) .filter(|p| p.namespace().ends_with('#') || p.namespace().ends_with('/')) @@ -279,11 +204,8 @@ pub fn prefix_completion_helper<'a>( return None; } - let completion = lov.as_completion( - lang, - word.range.clone(), - extra_edits(&lov.name(), &lov.namespace()), - ); + let completion = + lov.as_completion(lang, word.range, extra_edits(lov.name(), lov.namespace())); suggested.insert(lov.name().to_string()); Some(completion) @@ -408,3 +330,78 @@ pub fn rdf_lov_undefined_prefix_completion( ); } } + +#[cfg(test)] +mod shorten_tests { + use super::*; + + fn prefixes(decls: &[(&str, &str)]) -> Prefixes { + Prefixes( + decls + .iter() + .map(|(p, u)| Prefix { + prefix: p.to_string(), + url: crate::lsp_types::Url::parse(u).unwrap(), + }) + .collect(), + crate::lsp_types::Url::parse("file:///doc.ttl").unwrap(), + ) + } + + #[test] + fn local_names() { + for ok in [ + "", + "name", + "Name_1", + "a.b", + "1abc", + "a:b", + "caf\u{e9}", + "a%20b", + "a-b", + ] { + assert!(is_local_name(ok), "{ok:?} should be valid"); + } + for bad in [ + "a/b", "a#b", "a.", "-a", ".a", "a b", "a?b", "a%2", "a~b", "a,b", + ] { + assert!(!is_local_name(bad), "{bad:?} should be invalid"); + } + } + + #[test] + fn shorten_only_to_valid_prefixed_names() { + let p = prefixes(&[("rml", "http://w3id.org/rml/")]); + assert_eq!( + p.shorten("http://w3id.org/rml/TriplesMap").as_deref(), + Some("rml:TriplesMap") + ); + assert_eq!(p.shorten("http://w3id.org/rml/shapes/X"), None); + assert_eq!( + p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(), + Some("rml:shapes/X") + ); + assert_eq!(p.shorten("http://other.test/x"), None); + } + + #[test] + fn longest_namespace_wins() { + let p = prefixes(&[ + ("rml", "http://w3id.org/rml/"), + ("rmlsh", "http://w3id.org/rml/shapes/"), + ]); + assert_eq!( + p.shorten("http://w3id.org/rml/shapes/X").as_deref(), + Some("rmlsh:X") + ); + assert_eq!( + p.shorten_compact("http://w3id.org/rml/shapes/X").as_deref(), + Some("rmlsh:X") + ); + assert_eq!( + p.shorten("http://w3id.org/rml/source").as_deref(), + Some("rml:source") + ); + } +} diff --git a/core/src/systems/prefix_diagnostics.rs b/core/src/systems/prefix_diagnostics.rs index 62a61586c4..84293e594b 100644 --- a/core/src/systems/prefix_diagnostics.rs +++ b/core/src/systems/prefix_diagnostics.rs @@ -131,7 +131,7 @@ pub fn prefix_diagnostic_helper<'a>( let mut diags_by_prefix: HashMap<&str, Vec> = HashMap::new(); for (prefix_name, range) in &undefined_occurrences { let diag = Diagnostic { - range: range.clone(), + range: *range, severity: Some(DiagnosticSeverity::ERROR), message: format!("Undefined prefix \"{}\"", prefix_name), ..Default::default() diff --git a/core/src/systems/prefix_hover.rs b/core/src/systems/prefix_hover.rs index 7c5da358f8..fb684b97dd 100644 --- a/core/src/systems/prefix_hover.rs +++ b/core/src/systems/prefix_hover.rs @@ -147,7 +147,7 @@ pub fn hover_prefix( req.0.push(md); if req.1.is_none() { - req.1 = Some(prefix.range.clone()); + req.1 = Some(prefix.range); } } } @@ -170,7 +170,7 @@ pub fn goto_prefix( // lands on the file(s) the server loads for this prefix: one location per // configured ontology when several describe the namespace. let mut targets: Vec = - namespace_sources(&fs, &prefix.namespace, &prefix.name, &preferred, &locals) + namespace_sources(&fs, &prefix.namespace, &prefix.name, &preferred, locals) .into_iter() .map(|s| s.url) .collect(); diff --git a/core/src/systems/properties/query.rs b/core/src/systems/properties/query.rs index f1dfb299a7..8de51ced53 100644 --- a/core/src/systems/properties/query.rs +++ b/core/src/systems/properties/query.rs @@ -16,39 +16,34 @@ pub fn find_classes( let mut definitions = HashMap::new(); if let QueryResults::Solutions(solutions) = crate::store::union_query(include_str!("../../queries/class_definitions.sparql"))? - .on_store(&store) + .on_store(store) .execute() .ok()? { - for solution in solutions { - if let Ok(solution) = solution { - let class = solution.get("class").unwrap(); - let title = solution.get("title"); - let description = solution.get("description"); - - match (NamedNode::try_from(class.clone()),) { - (Ok(class),) => { - let v = definitions - .entry(class.clone()) - .or_insert_with(|| DefinedClass { - term: MyTerm::named_node(class.as_str(), 0..0).to_owned(), - locations: std::collections::HashSet::new(), - titles: Default::default(), - descriptions: Default::default(), - }); - - if let Some(title) = title.and_then(|x| Literal::try_from(x.clone()).ok()) { - v.titles.insert(title.value(), title.language()); - } - - if let Some(description) = - description.and_then(|x| Literal::try_from(x.clone()).ok()) - { - v.descriptions - .insert(description.value(), description.language()); - } - } - _ => {} + for solution in solutions.flatten() { + let class = solution.get("class").unwrap(); + let title = solution.get("title"); + let description = solution.get("description"); + + if let (Ok(class),) = (NamedNode::try_from(class.clone()),) { + let v = definitions + .entry(class.clone()) + .or_insert_with(|| DefinedClass { + term: MyTerm::named_node(class.as_str(), 0..0).to_owned(), + locations: std::collections::HashSet::new(), + titles: Default::default(), + descriptions: Default::default(), + }); + + if let Some(title) = title.and_then(|x| Literal::try_from(x.clone()).ok()) { + v.titles.insert(title.value(), title.language()); + } + + if let Some(description) = + description.and_then(|x| Literal::try_from(x.clone()).ok()) + { + v.descriptions + .insert(description.value(), description.language()); } } } @@ -66,57 +61,52 @@ pub fn find_properties(store: &oxigraph::store::Store) -> Option { - let v = definitions - .entry(class.as_str().to_string()) - .or_insert_with(|| DefinedProperty { - term: MyTerm::named_node(class.as_str(), 0..0).to_owned(), - locations: std::collections::HashSet::new(), - titles: Default::default(), - descriptions: Default::default(), - ranges: std::collections::HashSet::new(), - domains: std::collections::HashSet::new(), - }); - - if let Some(title) = title.and_then(|x| Literal::try_from(x.clone()).ok()) { - v.titles.insert(title.value(), title.language()); - } - - if let Some(description) = - description.and_then(|x| Literal::try_from(x.clone()).ok()) - { - v.descriptions - .insert(description.value(), description.language()); - } - if let Some(domain) = domain { - v.domains.insert(domain); - } - - if let Some(range) = range { - v.ranges.insert(range); - } - } - _ => {} + for solution in solutions.flatten() { + let class = solution.get("property").unwrap(); + let title = solution.get("title"); + let description = solution.get("description"); + + let range = solution + .get("range") + .and_then(|r| NamedNode::try_from(r.clone()).ok()) + .map(|r| MyTerm::named_node(r.as_str(), 0..0).to_owned()); + let domain = solution + .get("domain") + .and_then(|r| NamedNode::try_from(r.clone()).ok()) + .map(|r| MyTerm::named_node(r.as_str(), 0..0).to_owned()); + + if let (Ok(class),) = (NamedNode::try_from(class.clone()),) { + let v = definitions + .entry(class.as_str().to_string()) + .or_insert_with(|| DefinedProperty { + term: MyTerm::named_node(class.as_str(), 0..0).to_owned(), + locations: std::collections::HashSet::new(), + titles: Default::default(), + descriptions: Default::default(), + ranges: std::collections::HashSet::new(), + domains: std::collections::HashSet::new(), + }); + + if let Some(title) = title.and_then(|x| Literal::try_from(x.clone()).ok()) { + v.titles.insert(title.value(), title.language()); + } + + if let Some(description) = + description.and_then(|x| Literal::try_from(x.clone()).ok()) + { + v.descriptions + .insert(description.value(), description.language()); + } + if let Some(domain) = domain { + v.domains.insert(domain); + } + + if let Some(range) = range { + v.ranges.insert(range); } } } diff --git a/core/src/systems/properties/systems.rs b/core/src/systems/properties/systems.rs index 431307349f..bf5af18946 100644 --- a/core/src/systems/properties/systems.rs +++ b/core/src/systems/properties/systems.rs @@ -46,14 +46,14 @@ pub fn complete_class( if to_beat.starts_with(&token.text) { let mut completion = SimpleCompletion::new( CompletionItemKind::CLASS, - format!("{}", to_beat), + to_beat.to_string(), TextEdit { - range: token.range.clone(), + range: token.range, new_text: to_beat.to_string(), }, ) .label_description(class.full_title()) - .documentation(class.full_docs(&hierarchy, &prefixes)); + .documentation(class.full_docs(&hierarchy, prefixes)); if superclasses.contains(class.term.as_str()) { completion.kind = CompletionItemKind::INTERFACE; @@ -87,7 +87,7 @@ pub fn hover_class( request.0.push(format!( "## {}\n\n{}", class.full_title(), - class.full_docs(&hierarchy, &prefixes) + class.full_docs(&hierarchy, prefixes) )); } } @@ -159,17 +159,17 @@ pub fn complete_properties( let to_beat = lang.write_iri(prefixes, &property.term.value); - if to_beat.starts_with(&bare_text) { + if to_beat.starts_with(bare_text) { let mut completion = SimpleCompletion::new( CompletionItemKind::ENUM_MEMBER, to_beat.to_string(), TextEdit { - range: token.range.clone(), + range: token.range, new_text: lang.quote(&to_beat), }, ) - .label_description(&property.full_title()) - .documentation(&property.full_docs(&prefixes)); + .label_description(property.full_title()) + .documentation(property.full_docs(prefixes)); if correct_domain { completion.kind = CompletionItemKind::FIELD; @@ -211,7 +211,7 @@ pub fn hover_property( request.0.push(format!( "## {}\n\n{}", c.full_title(), - c.full_docs(&prefixes) + c.full_docs(prefixes) )); } } diff --git a/core/src/systems/properties/types.rs b/core/src/systems/properties/types.rs index 71e0351b39..038e6fbfde 100644 --- a/core/src/systems/properties/types.rs +++ b/core/src/systems/properties/types.rs @@ -149,7 +149,7 @@ impl DefinedProperty { docs += ", " } first = false; - docs += range.as_ref().map(|x| x.as_str()).unwrap_or(r.as_str()); + docs += range.as_deref().unwrap_or(r.as_str()); } } @@ -165,7 +165,7 @@ impl DefinedProperty { docs += ", " } first = false; - docs += range.as_ref().map(|x| x.as_str()).unwrap_or(r.as_str()); + docs += range.as_deref().unwrap_or(r.as_str()); } } diff --git a/core/src/systems/shapes/data.rs b/core/src/systems/shapes/data.rs index 5cbc8ee991..f8f997839b 100644 --- a/core/src/systems/shapes/data.rs +++ b/core/src/systems/shapes/data.rs @@ -95,7 +95,7 @@ impl NeighsRDF for Rdf { } } -impl<'b> TryInto for MyTerm<'static> { +impl TryInto for MyTerm<'static> { type Error = (); fn try_into(self) -> std::result::Result { @@ -126,7 +126,7 @@ impl<'b> TryInto for MyTerm<'static> { return Err(()); } }; - return Ok(output); + Ok(output) } } @@ -216,9 +216,8 @@ impl Literal for MyTerm<'static> { } fn lang(&self) -> Option { - match &self.context { - TermContext::LangTag(cow) => return r_term::literal::Lang::new(cow.as_ref()).ok(), - _ => {} + if let TermContext::LangTag(cow) = &self.context { + return r_term::literal::Lang::new(cow.as_ref()).ok(); } None } @@ -281,7 +280,7 @@ fn dt_to_slit(value: &str, dt: &str) -> r_term::literal::ConcreteLiteral { SLiteral::DatatypeLiteral { lexical_form: value.to_string(), - datatype: prefixmap::IriRef::Iri(IriS::new_unchecked(&dt)), + datatype: prefixmap::IriRef::Iri(IriS::new_unchecked(dt)), } } @@ -474,12 +473,7 @@ impl rudof_rdf::rdf_core::Rdf for Rdf { fn term_as_sliteral(term: &Self::Term) -> Result { let lit = Self::term_as_literal(term)?; - let slit = - >::try_into(lit.clone()) - .map_err(|_| RDFError::LiteralAsSLiteral { - literal: lit.to_string(), - })?; - Ok(slit) + Ok(lit.into()) } fn term_as_subject(term: &Self::Term) -> Result { @@ -544,7 +538,7 @@ impl rudof_rdf::rdf_core::Rdf for Rdf { fn compare(&self, term1: &Self::Term, term2: &Self::Term) -> Result { term1 - .partial_cmp(&term2) + .partial_cmp(term2) .ok_or_else(|| RDFError::ComparisonError { term1: term1.to_string(), term2: term2.to_string(), diff --git a/core/src/systems/shapes/mod.rs b/core/src/systems/shapes/mod.rs index b5eac5979e..aeec439bcf 100644 --- a/core/src/systems/shapes/mod.rs +++ b/core/src/systems/shapes/mod.rs @@ -173,10 +173,9 @@ pub fn validate_shapes( for res in all { if let Some(m) = res.message() { - write!(&mut writer, "{}\n", m).unwrap(); + writeln!(&mut writer, "{}", m).unwrap(); } else { - write!(&mut writer, "Component {} ", res.component().to_string()) - .unwrap(); + write!(&mut writer, "Component {} ", res.component()).unwrap(); } } @@ -191,9 +190,9 @@ pub fn validate_shapes( let id = MyTerm::from(shape.id().clone()); if id.ty == Some(sophia_api::term::TermKind::Iri) { - write!(&mut writer, "({})\n", id.value).unwrap(); + writeln!(&mut writer, "({})", id.value).unwrap(); } else { - write!(&mut writer, "\n",).unwrap(); + writeln!(&mut writer,).unwrap(); } if let Some(source) = res.source().cloned() { diff --git a/core/src/systems/shapes/model.rs b/core/src/systems/shapes/model.rs index cfca72ae43..95411699ca 100644 --- a/core/src/systems/shapes/model.rs +++ b/core/src/systems/shapes/model.rs @@ -429,7 +429,7 @@ pub(crate) fn merge(into: &mut Vec, p: Property) { } pub(crate) fn local_name(iri: &str) -> &str { - iri.rsplit(|c| c == '#' || c == '/' || c == ':') + iri.rsplit(['#', '/', ':']) .find(|s| !s.is_empty()) .unwrap_or(iri) } diff --git a/core/src/util/triple.rs b/core/src/util/triple.rs index c60ea12668..d731a396ce 100644 --- a/core/src/util/triple.rs +++ b/core/src/util/triple.rs @@ -2,7 +2,6 @@ use std::{ borrow::{Borrow, Cow}, hash::Hash, sync::Arc, - usize, }; use bevy_ecs::prelude::*; @@ -137,7 +136,6 @@ pub fn get_current_triple( (TripleTarget::Object, &t.object.span, t), ] }) - .into_iter() .filter(|x| x.1.contains(&offset)) .min_by_key(|x| x.1.end - x.1.start) { @@ -237,30 +235,34 @@ impl<'b, 'a> TryFrom<&'b MyQuad<'a>> for oxigraph::model::Quad { } impl<'a> MyQuad<'a> { + /// This quad in oxigraph's model, in the named graph `graph`. `None` when a + /// term cannot be represented (e.g. a literal subject). pub fn into_oxi_graph( &self, graph: impl TryInto, - ) -> Result { - let graph = graph.try_into().map_err(|_| ())?; - let graph = oxigraph::model::NamedOrBlankNode::try_from(graph).map_err(|_| ())?; + ) -> Option { + let graph = graph.try_into().ok()?; + let graph = oxigraph::model::NamedOrBlankNode::try_from(graph).ok()?; let graph = oxigraph::model::GraphName::from(graph); self.into_oxi(Some(graph)) } + /// This quad in oxigraph's model, in `graph` (the default graph when + /// `None`). `None` when a term cannot be represented. pub fn into_oxi( &self, graph: Option, - ) -> Result { - let subject = oxigraph::model::Term::try_from(&self.subject)?; - let predicate = oxigraph::model::Term::try_from(&self.predicate)?; - let object = oxigraph::model::Term::try_from(&self.object)?; + ) -> Option { + let subject = oxigraph::model::Term::try_from(&self.subject).ok()?; + let predicate = oxigraph::model::Term::try_from(&self.predicate).ok()?; + let object = oxigraph::model::Term::try_from(&self.object).ok()?; let graph = graph.unwrap_or_default(); - let subject = oxigraph::model::NamedOrBlankNode::try_from(subject).map_err(|_| ())?; - let predicate = oxigraph::model::NamedNode::try_from(predicate).map_err(|_| ())?; + let subject = oxigraph::model::NamedOrBlankNode::try_from(subject).ok()?; + let predicate = oxigraph::model::NamedNode::try_from(predicate).ok()?; - Ok(oxigraph::model::Quad::new( + Some(oxigraph::model::Quad::new( subject, predicate, object, graph, )) } @@ -319,7 +321,7 @@ impl<'a, 'b> TryFrom<&'b MyTerm<'a>> for oxigraph::model::Term { return Err(()); } }; - return Ok(output); + Ok(output) } } @@ -373,11 +375,7 @@ pub struct MyTerm<'a> { } impl<'a> PartialOrd for MyTerm<'a> { fn partial_cmp(&self, other: &Self) -> Option { - match self.value.partial_cmp(&other.value) { - Some(core::cmp::Ordering::Equal) => {} - ord => return ord, - } - self.ty.partial_cmp(&other.ty) + Some(Ord::cmp(self, other)) } } impl<'a> Ord for MyTerm<'a> { @@ -422,7 +420,7 @@ impl<'a> MyTerm<'a> { let value = Cow::Owned(self.value.to_string()); MyTerm { value, - ty: self.ty.clone(), + ty: self.ty, span: self.span.clone(), context: self.context.to_owned(), } @@ -570,7 +568,7 @@ impl<'a> Triples2<'a> { } } - pub fn imports(&self, cb: impl FnMut(IriRef>) -> ()) { + pub fn imports(&self, cb: impl FnMut(IriRef>)) { if let Some(ref base) = self.base { self.triples .quads_matching([base], [owl::imports], Any, Any) @@ -580,7 +578,7 @@ impl<'a> Triples2<'a> { } } - pub fn sub_class_of(&self, mut cb: impl FnMut(IriRef>, IriRef>) -> ()) { + pub fn sub_class_of(&self, mut cb: impl FnMut(IriRef>, IriRef>)) { self.triples .quads_matching(Any, [rdfs::subClassOf], Any, Any) .flatten() diff --git a/e2e/Cargo.toml b/e2e/Cargo.toml index 78d5b373d4..75e58adf31 100644 --- a/e2e/Cargo.toml +++ b/e2e/Cargo.toml @@ -23,3 +23,6 @@ swls-test-utils = { path = "../test-utils/" } [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } + +[lints] +workspace = true diff --git a/lang-jsonld/Cargo.toml b/lang-jsonld/Cargo.toml index 8a01a18c3d..37c9c85eb6 100644 --- a/lang-jsonld/Cargo.toml +++ b/lang-jsonld/Cargo.toml @@ -29,3 +29,6 @@ oxigraph = { version = "0.5.3", features = ["rdf-12"], default-fea [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } swls-test-utils = { path = "../test-utils/" } + +[lints] +workspace = true diff --git a/lang-jsonld/src/ecs/completion.rs b/lang-jsonld/src/ecs/completion.rs index d442eea783..5cd31069fb 100644 --- a/lang-jsonld/src/ecs/completion.rs +++ b/lang-jsonld/src/ecs/completion.rs @@ -210,14 +210,14 @@ pub fn add_to_context( // ── prefix completion ───────────────────────────────────────────────────────── -/// JSON-LD prefix completion from LOV / prefix.cc. -/// -/// Suggests prefixes that are not yet declared in the document's `@context` and -/// produces an additional [`TextEdit`] via [`add_to_context`] that inserts the -/// new prefix declaration into the `@context` value. -/// -/// Uses [`DynLang::quote`] so the inserted predicate text is correctly wrapped -/// in JSON string quotes (e.g. `"foaf:"`). +// JSON-LD prefix completion from LOV / prefix.cc. +// +// Suggests prefixes that are not yet declared in the document's `@context` and +// produces an additional `TextEdit` via `add_to_context` that inserts the +// new prefix declaration into the `@context` value. +// +// Uses `DynLang::quote` so the inserted predicate text is correctly wrapped +// in JSON string quotes (e.g. `"foaf:"`). // #[instrument(skip(query, lovs, prefix_cc, config))] // pub fn jsonld_lov_undefined_prefix_completion( // mut query: Query< @@ -418,7 +418,7 @@ pub fn jsonld_property_completion( CompletionItemKind::FIELD, compact.clone(), TextEdit { - range: token.range.clone(), + range: token.range, new_text: format!("\"{}\"", compact), }, ); diff --git a/lang-jsonld/src/ecs/mod.rs b/lang-jsonld/src/ecs/mod.rs index d3e8bdd666..c011bc5dd1 100644 --- a/lang-jsonld/src/ecs/mod.rs +++ b/lang-jsonld/src/ecs/mod.rs @@ -241,8 +241,8 @@ fn fetch_from_web( cq.push(move |world: &mut World| { if world .query::<(Entity, &Label)>() - .iter(&world) - .find(|x| x.1.as_str() == &url) + .iter(world) + .find(|x| x.1.as_str() == url) .is_none() { world.spawn((Source(resp.body), Label(label))); @@ -260,8 +260,8 @@ fn fetch_from_web( cq.push(move |world: &mut World| { if world .query::<(Entity, &Label)>() - .iter(&world) - .find(|x| x.1.as_str() == &url) + .iter(world) + .find(|x| x.1.as_str() == url) .is_none() { let item = TextDocumentItem { @@ -443,7 +443,7 @@ fn parse_jsonld_system( let gn = parse.green_node.clone(); let base = label.0.to_string(); let span = 0..source.0.len(); - let e = entity.clone(); + let e = entity; let mut sender = sender.clone(); let cjs_contexts = cjs_contexts.clone(); client.spawn_local(move || async move { diff --git a/lang-jsonld/src/lib.rs b/lang-jsonld/src/lib.rs index 7695547524..ac4c4f9ae1 100644 --- a/lang-jsonld/src/lib.rs +++ b/lang-jsonld/src/lib.rs @@ -164,11 +164,10 @@ impl LangHelper for JsonLdHelper { types: Vec>, ) -> Option { let (label, position) = if let Some(lt) = last_type { - if let Some(pos) = offset_to_position(lt.end, &rope) { + { + let pos = offset_to_position(lt.end, rope)?; let label = format!(", {}", types.join(", ")); (label, pos) - } else { - return None; } } else { let offset = if rope.char_at_byte(subject.start) == Some('[') { @@ -177,7 +176,8 @@ impl LangHelper for JsonLdHelper { subject.end }; - if let Some(pos) = offset_to_position(offset + 1, &rope) { + { + let pos = offset_to_position(offset + 1, rope)?; let label = if types.len() == 1 { format!(r#" "@type": "{}";"#, types[0]) } else { @@ -191,12 +191,10 @@ impl LangHelper for JsonLdHelper { ) }; (label, pos) - } else { - return None; } }; - return Some(swls_core::lsp_types::InlayHint { + Some(swls_core::lsp_types::InlayHint { position, label: swls_core::lsp_types::InlayHintLabel::String(label), kind: None, @@ -205,7 +203,7 @@ impl LangHelper for JsonLdHelper { padding_left: None, padding_right: None, data: None, - }); + }) } } @@ -231,8 +229,8 @@ pub fn setup_world(world: &mut World) if source.0.contains("\"@context\"") { commands .entity(entity) - .insert(JsonLdLang::default()) - .insert(DynLang(Box::new(JsonLdHelper::default()))); + .insert(JsonLdLang) + .insert(DynLang(Box::new(JsonLdHelper))); } } }, @@ -385,7 +383,6 @@ fn goto_cjs( None }; let st: &str = triple_term_str - .as_deref() .or(context_expanded.as_deref()) .unwrap_or(raw_token); @@ -434,7 +431,7 @@ fn goto_cjs( if triple_term_str.is_none() { // Import IRIs: strip any fragment, then resolve to a local file path. - let target = resolve_iri(&label.as_str(), st); + let target = resolve_iri(label.as_str(), st); if let Ok(uri) = swls_core::lsp_types::Url::parse(&target) { req.0.push(Location { uri, @@ -465,7 +462,7 @@ mod fs { async fn read_to_string(&self, url: &Url) -> Result { self.0 .0 - .read_file(&url) + .read_file(url) .await .ok_or(ComponentsJsError::General(format!( "Failed to read file {}", @@ -674,7 +671,6 @@ fn start_jsonld( }); let _ = commands.unbounded_send(command_queue); } - () }; client.spawn(thing); } else { diff --git a/lang-n3/Cargo.toml b/lang-n3/Cargo.toml index 147d05d3a6..582336e8c7 100644 --- a/lang-n3/Cargo.toml +++ b/lang-n3/Cargo.toml @@ -24,3 +24,6 @@ swls-core = { workspace = true } [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } swls-test-utils = { path = "../test-utils/" } + +[lints] +workspace = true diff --git a/lang-n3/src/ecs/mod.rs b/lang-n3/src/ecs/mod.rs index dfaf7a7b2d..a2da2b3f22 100644 --- a/lang-n3/src/ecs/mod.rs +++ b/lang-n3/src/ecs/mod.rs @@ -142,6 +142,36 @@ fn parse_n3_system( } } +pub(crate) fn format_n3_system( + mut query: Query<(&RopeC, &Wrapped, &mut FormatRequest), With>, + config: Res, +) { + use swls_core::lsp_types::{Position, Range}; + if !config.config.local.format.n3() { + tracing::debug!("N3 formatting disabled by config"); + return; + } + for (source, node, mut request) in &mut query { + if request.0.is_some() { + tracing::debug!("Didn't format with the n3 format system, already formatted"); + continue; + } + tracing::debug!("Formatting with n3 format system"); + + let root = rowan::SyntaxNode::new_root(node.0.clone()); + + let formatted = rdf_parsers::n3::format::format(&root, 80); + + request.0 = Some(vec![swls_core::lsp_types::TextEdit::new( + Range::new( + Position::new(0, 0), + Position::new(source.0.len_lines() as u32 + 1, 0), + ), + formatted, + )]); + } +} + #[cfg(test)] mod tests { use super::*; @@ -217,7 +247,7 @@ mod tests { world.run_schedule(ParseLabel); let mut messages: Vec = Vec::new(); - while let Ok(Some(item)) = rx.try_next() { + while let Ok(item) = rx.try_recv() { for d in item.diagnostics { messages.push(d.message); } @@ -253,33 +283,3 @@ mod tests { ); } } - -pub(crate) fn format_n3_system( - mut query: Query<(&RopeC, &Wrapped, &mut FormatRequest), With>, - config: Res, -) { - use swls_core::lsp_types::{Position, Range}; - if !config.config.local.format.n3() { - tracing::debug!("N3 formatting disabled by config"); - return; - } - for (source, node, mut request) in &mut query { - if request.0.is_some() { - tracing::debug!("Didn't format with the n3 format system, already formatted"); - continue; - } - tracing::debug!("Formatting with n3 format system"); - - let root = rowan::SyntaxNode::new_root(node.0.clone()); - - let formatted = rdf_parsers::n3::format::format(&root, 80); - - request.0 = Some(vec![swls_core::lsp_types::TextEdit::new( - Range::new( - Position::new(0, 0), - Position::new(source.0.len_lines() as u32 + 1, 0), - ), - formatted, - )]); - } -} diff --git a/lang-rdf-base/Cargo.toml b/lang-rdf-base/Cargo.toml index a30c1830e3..c6d7910bc3 100644 --- a/lang-rdf-base/Cargo.toml +++ b/lang-rdf-base/Cargo.toml @@ -16,3 +16,6 @@ bevy_ecs.workspace = true tracing.workspace = true swls-core = { workspace = true } rdf-parsers.workspace = true + +[lints] +workspace = true diff --git a/lang-rdf-base/src/lib.rs b/lang-rdf-base/src/lib.rs index 3085fe9505..b7dcdfd519 100644 --- a/lang-rdf-base/src/lib.rs +++ b/lang-rdf-base/src/lib.rs @@ -188,7 +188,7 @@ mod tokens { // JSON-LD, anonymous blank nodes have a Spanned span that covers the // entire nested { } object, so stamping ENUM_MEMBER here would wipe // out all inner coloring β€” inner triples handle their own content. - Term::BlankNode(BlankNode::Named(_, _)) => return, + Term::BlankNode(BlankNode::Named(_, _)) => (), Term::BlankNode(BlankNode::Unnamed(pos, _, _)) => { for po in pos { for o in &po.object { @@ -205,7 +205,7 @@ mod tokens { let dt = la.as_ref().map(|x| Term::NamedNode(x.clone())); add_term(&dt, ttc, kind, source); } - _ => return, + _ => (), } } diff --git a/lang-rdf-base/src/traits.rs b/lang-rdf-base/src/traits.rs index 8ad51d6525..387ba81250 100644 --- a/lang-rdf-base/src/traits.rs +++ b/lang-rdf-base/src/traits.rs @@ -316,6 +316,8 @@ pub enum TurtleSimpleError { // ── Turtle extension trait ──────────────────────────────────────────────────── pub trait TurtleExt { fn get_simple_triples<'a>(&'a self) -> Result, TurtleSimpleError>; + // Public API used across crates; renaming it is out of scope for lint cleanup. + #[allow(clippy::wrong_self_convention)] fn into_triples<'a>(&self, triples: Vec>) -> Triples2<'a>; fn shorten(&self, url: &str) -> Option; } diff --git a/lang-rdf-base/src/triples.rs b/lang-rdf-base/src/triples.rs index 28c33e8e84..66bd096dab 100644 --- a/lang-rdf-base/src/triples.rs +++ b/lang-rdf-base/src/triples.rs @@ -9,5 +9,7 @@ use swls_core::prelude::MyQuad; /// The implementation must be in a crate that owns either this trait or the element type. pub trait IntoTriples { type Error: Debug; + // Public API used across crates; renaming it is out of scope for lint cleanup. + #[allow(clippy::wrong_self_convention)] fn into_triples(&self) -> Result>, Self::Error>; } diff --git a/lang-sparql/Cargo.toml b/lang-sparql/Cargo.toml index a9bd2b1b9b..fe6c4df2da 100644 --- a/lang-sparql/Cargo.toml +++ b/lang-sparql/Cargo.toml @@ -25,3 +25,6 @@ swls-core = { workspace = true } [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } swls-test-utils = { path = "../test-utils/" } + +[lints] +workspace = true diff --git a/lang-sparql/src/ecs/mod.rs b/lang-sparql/src/ecs/mod.rs index c4d9ccd890..0083a079e8 100644 --- a/lang-sparql/src/ecs/mod.rs +++ b/lang-sparql/src/ecs/mod.rs @@ -249,7 +249,7 @@ pub fn variable_completion( CompletionItemKind::VARIABLE, t.clone(), swls_core::lsp_types::TextEdit { - range: token.range.clone(), + range: token.range, new_text: t, }, ); diff --git a/lang-trig/Cargo.toml b/lang-trig/Cargo.toml index d124b04a6a..a3c39bcd44 100644 --- a/lang-trig/Cargo.toml +++ b/lang-trig/Cargo.toml @@ -24,3 +24,6 @@ swls-core = { workspace = true } [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } swls-test-utils = { path = "../test-utils/" } + +[lints] +workspace = true diff --git a/lang-turtle/Cargo.toml b/lang-turtle/Cargo.toml index 415ffc1d5e..3e18a9482e 100644 --- a/lang-turtle/Cargo.toml +++ b/lang-turtle/Cargo.toml @@ -25,3 +25,6 @@ rowan = "0.16.1" [dev-dependencies] test-log = { version = "0.2.19", features = ["trace"] } swls-test-utils = { path = "../test-utils/" } + +[lints] +workspace = true diff --git a/lang-turtle/src/config.rs b/lang-turtle/src/config.rs index 68f623f4c7..587b6d7f1e 100644 --- a/lang-turtle/src/config.rs +++ b/lang-turtle/src/config.rs @@ -15,7 +15,9 @@ pub fn extract_known_shapes_from_config, sender: Res, ) { - for on in config.config.local.shapes.iter().cloned() { + for on in config.config.local.shapes.iter() { + // Owned: it moves into the spawned future. + let on = on.clone(); let c = client.clone(); let fs = fs.clone(); let sender = sender.0.clone(); @@ -69,7 +71,9 @@ pub fn extract_known_prefixes_from_config, sender: Res, ) { - for on in config.config.local.ontologies.iter().cloned() { + for on in config.config.local.ontologies.iter() { + // Owned: it moves into the spawned future. + let on = on.clone(); let c = client.clone(); let fs = fs.clone(); let sender = sender.0.clone(); diff --git a/lang-turtle/src/ecs/completion.rs b/lang-turtle/src/ecs/completion.rs index c32f3eac31..9e17529384 100644 --- a/lang-turtle/src/ecs/completion.rs +++ b/lang-turtle/src/ecs/completion.rs @@ -51,7 +51,7 @@ pub fn subject_completion( subj.to_string(), swls_core::lsp_types::TextEdit { new_text, - range: word.range.clone(), + range: word.range, }, ) .documentation(format!("Subject from {}", label.0)), diff --git a/lang-turtle/src/ecs/mod.rs b/lang-turtle/src/ecs/mod.rs index 4e6115a071..ecc16b023e 100644 --- a/lang-turtle/src/ecs/mod.rs +++ b/lang-turtle/src/ecs/mod.rs @@ -70,7 +70,7 @@ mod tests { let mut last_diags = move || -> Vec { let mut items: Vec = Vec::new(); - while let Ok(Some(x)) = rx.try_next() { + while let Ok(x) = rx.try_recv() { items.push(x); } items diff --git a/lang-turtle/src/prefix.rs b/lang-turtle/src/prefix.rs index 7ecd75c478..b90fe9bd78 100644 --- a/lang-turtle/src/prefix.rs +++ b/lang-turtle/src/prefix.rs @@ -17,7 +17,7 @@ pub async fn find(location: &str, fs: &Fs, client: &impl Client) -> Option Option Option { } pub fn prefix_from_url(url: &Url) -> Option<(Cow<'static, str>, Cow<'static, str>)> { - let segments = url.path_segments()?; - let last = segments.last()?; + let mut segments = url.path_segments()?; + let last = segments.next_back()?; let prefix = last.rsplit_once('.').map(|(x, _)| x).unwrap_or(last); let prefix: Cow<'static, str> = Cow::Owned(prefix.to_string()); diff --git a/lov/Cargo.toml b/lov/Cargo.toml index 7e38f1582d..43159204b2 100644 --- a/lov/Cargo.toml +++ b/lov/Cargo.toml @@ -14,3 +14,6 @@ homepage.workspace = true [dependencies] bevy_ecs.workspace = true + +[lints] +workspace = true diff --git a/lov/src/lib.rs b/lov/src/lib.rs index 2994981e5f..9a99c64e91 100644 --- a/lov/src/lib.rs +++ b/lov/src/lib.rs @@ -13,4 +13,4 @@ pub struct LocalPrefix { pub rank: usize, } -pub const LOCAL_PREFIXES: &'static [LocalPrefix] = min_prefixes::LOCAL_PREFIXES; +pub const LOCAL_PREFIXES: &[LocalPrefix] = min_prefixes::LOCAL_PREFIXES; diff --git a/lov/src/min_prefixes.rs b/lov/src/min_prefixes.rs index c012162737..a7b9c9ff4a 100644 --- a/lov/src/min_prefixes.rs +++ b/lov/src/min_prefixes.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use super::LocalPrefix; -pub const LOCAL_PREFIXES: &'static [LocalPrefix] = &[ +pub const LOCAL_PREFIXES: &[LocalPrefix] = &[ LocalPrefix { location: Cow::Borrowed("http://xmlns.com/foaf/0.1/"), namespace: Cow::Borrowed("http://xmlns.com/foaf/0.1/"), diff --git a/swls/Cargo.toml b/swls/Cargo.toml index 1349676ea3..46f59dcc72 100644 --- a/swls/Cargo.toml +++ b/swls/Cargo.toml @@ -36,3 +36,6 @@ default = ["tower-lsp/runtime-tokio"] [build-dependencies] vergen = { version = "8", default-features = false, features = ["build"] } + +[lints] +workspace = true diff --git a/swls/src/client.rs b/swls/src/client.rs index 61e2f4209e..77d314468b 100644 --- a/swls/src/client.rs +++ b/swls/src/client.rs @@ -32,6 +32,12 @@ pub type Job = Box LocalFuture + Send>; /// file and editors warn before a cached copy is edited. #[derive(Debug)] pub struct BinFs(PathBuf); +impl Default for BinFs { + fn default() -> Self { + Self::new() + } +} + impl BinFs { pub fn new() -> Self { let root = dirs::cache_dir() @@ -150,14 +156,14 @@ impl FsTrait for BinFs { Some(entries) } async fn is_file(&self, path: &Url) -> bool { - if let Some(p) = path.to_file_path().ok() { + if let Ok(p) = path.to_file_path() { p.is_file() } else { !path.as_str().ends_with('/') } } async fn is_dir(&self, path: &Url) -> bool { - if let Some(p) = path.to_file_path().ok() { + if let Ok(p) = path.to_file_path() { p.is_dir() } else { !path.as_str().ends_with('/') @@ -229,10 +235,10 @@ impl ClientSync for TowerClient { let client = ::reqwest::Client::new(); let builder = client.get(url); let builder = headers - .into_iter() + .iter() .fold(builder, |builder, (k, v)| builder.header(k, v)); - return async { + async { let url = m_url.map_err(|_| String::from("invalid url!"))?; if url.scheme() == "file" { let mut file = File::open(url.path()) @@ -241,7 +247,7 @@ impl ClientSync for TowerClient { let mut body = String::new(); file.read_to_string(&mut body) .await - .map_err(|_| format!("Failed to read file"))?; + .map_err(|_| "Failed to read file".to_string())?; let status = 200; let headers = Vec::new(); return Ok(Resp { @@ -279,7 +285,7 @@ impl ClientSync for TowerClient { status, }) } - .boxed(); + .boxed() } fn spawn_local(&self, f: F) diff --git a/swls/src/timings.rs b/swls/src/timings.rs index 43598fe8e8..22e7dd8f66 100644 --- a/swls/src/timings.rs +++ b/swls/src/timings.rs @@ -57,6 +57,12 @@ where } } +impl Default for TracingLayer { + fn default() -> Self { + Self::new() + } +} + impl TracingLayer { pub fn new() -> Self { let (sender, mut receiver) = mpsc::channel(100); diff --git a/test-utils/Cargo.toml b/test-utils/Cargo.toml index aafe2f30f1..d6be28c8ef 100644 --- a/test-utils/Cargo.toml +++ b/test-utils/Cargo.toml @@ -22,3 +22,6 @@ async-std = "1.13.2" swls-core = { path = "../core/" } glob = "0.3.3" + +[lints] +workspace = true diff --git a/test-utils/src/lib.rs b/test-utils/src/lib.rs index 45effb62a9..2d8725a786 100644 --- a/test-utils/src/lib.rs +++ b/test-utils/src/lib.rs @@ -166,7 +166,7 @@ impl ClientSync for TestClient { let mut headers = Vec::new(); async_std::task::sleep(Duration::from_millis(200)).await; headers.push(("Content-Type".to_string(), "text/turtle".to_string())); - let status = body.is_some().then_some(200).unwrap_or(404); + let status = if body.is_some() { 200 } else { 404 }; Ok(Resp { headers, body: body.unwrap_or_default(), @@ -200,6 +200,12 @@ impl TestFs { pub async fn empty(&self) {} } +impl Default for TestFs { + fn default() -> Self { + Self::new() + } +} + impl Drop for TestFs { fn drop(&mut self) { let _ = remove_dir_all(&self.0); @@ -253,24 +259,24 @@ impl FsTrait for TestFs { fs::write(fp, content.as_bytes()).await.ok() } - async fn read_dir(&self, path: &swls_core::lsp_types::Url) -> Option> { + async fn read_dir(&self, _path: &swls_core::lsp_types::Url) -> Option> { None } - async fn is_file(&self, path: &swls_core::lsp_types::Url) -> bool { + async fn is_file(&self, _path: &swls_core::lsp_types::Url) -> bool { true } - async fn is_dir(&self, path: &swls_core::lsp_types::Url) -> bool { + async fn is_dir(&self, _path: &swls_core::lsp_types::Url) -> bool { false } - async fn glob(&self, base: &Url, pattern: &str) -> Option> { + async fn glob(&self, _base: &Url, _pattern: &str) -> Option> { None } } pub fn setup_world( client: TestClient, - f: impl FnOnce(&mut World) -> (), + f: impl FnOnce(&mut World), ) -> (World, UnboundedReceiver) { let mut world = World::new(); setup_schedule_labels::(&mut world); @@ -326,7 +332,7 @@ pub fn create_file( } pub fn debug_world(world: &mut World) { - for e in world.query::().iter(&world) { + for e in world.query::().iter(world) { let e = world.entity(e); if let Some(l) = e.get:: ex:fo|;").as_deref(), Some("ex:fo")); + assert_eq!(at(" ex:fo|").as_deref(), Some("ex:fo")); + assert_eq!(at(" |ex:name .").as_deref(), Some("ex:name")); + assert_eq!(at(" ex:na|me .").as_deref(), Some("ex:name")); + } + + #[test] + fn punctuation_only_when_no_word_touches_the_cursor() { + assert_eq!(at(" a ex:C ;|").as_deref(), Some(";")); + assert_eq!(at(" ex:p [|").as_deref(), Some("[")); + } + + #[test] + fn whitespace_has_no_token() { + assert_eq!(at(" a ex:C ;\n |\n."), None); + assert_eq!(at(" ex:p [\n |\n] ."), None); + } +} + pub mod semantic_token { use crate::lsp_types::SemanticTokenType as STT; pub const BOOLEAN: STT = STT::new("boolean"); diff --git a/core/src/util/triple.rs b/core/src/util/triple.rs index d731a396ce..471f06cf43 100644 --- a/core/src/util/triple.rs +++ b/core/src/util/triple.rs @@ -25,7 +25,7 @@ use crate::{ /// [`Component`] used to indicate the term type of currently targeted /// [`Token`](`crate::prelude::Token`) in the Triple. -#[derive(Debug, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TripleTarget { Subject, Predicate, @@ -123,10 +123,9 @@ pub fn get_current_triple( continue; }; - // First try: find the narrowest triple whose span inclusively contains the cursor. - // Using inclusive end (<=) so the cursor at exactly span.end (e.g. after a partially - // written predicate or object) still matches. - + // First try: the narrowest term the cursor is on. A cursor sits between + // characters, so a term that ends at the cursor counts too (the term being + // typed, e.g. `ex:fo|`), after terms that contain it. if let Some((target, _, t)) = triples .iter() .flat_map(|t| { @@ -136,8 +135,8 @@ pub fn get_current_triple( (TripleTarget::Object, &t.object.span, t), ] }) - .filter(|x| x.1.contains(&offset)) - .min_by_key(|x| x.1.end - x.1.start) + .filter(|x| x.1.contains(&offset) || (x.1.end == offset && x.1.start < x.1.end)) + .min_by_key(|x| (!x.1.contains(&offset), x.1.end - x.1.start)) { tracing::debug!( "Narrowest triple at {} Component {:?} {} {:?} {} {:?} {} {:?} .", diff --git a/e2e/src/lib.rs b/e2e/src/lib.rs index c1f7296674..95703fcc6f 100644 --- a/e2e/src/lib.rs +++ b/e2e/src/lib.rs @@ -22,11 +22,10 @@ //! //! ## Position convention //! -//! Positions are 0-indexed `(line, character)` matching the LSP spec. The harness works at -//! the ECS level and does **not** apply the `Backend::adjust_position` -1 offset. Pass the -//! character index of the **first character of the token** you want resolved (not the cursor -//! position after the last typed character). This is consistent with the position values used -//! in the existing unit tests inside `lang-turtle`. +//! Positions are 0-indexed `(line, character)` LSP cursor positions, exactly as an editor +//! sends them and as the server receives them: a cursor sits *between* characters. A cursor +//! touching a word (inside it, or right after it, e.g. `ex:fo|;`) belongs to that word; in +//! whitespace it belongs to no token (see `swls_core::util::token::token_at_cursor`). #![allow(dead_code)] @@ -244,8 +243,7 @@ impl LspHarness { /// Request completion items at `(line, character)`. /// - /// Positions are 0-indexed as in the LSP spec. The character value is the index of the - /// **first character of the token** being completed (consistent with the existing unit tests). + /// Positions are 0-indexed LSP cursor positions (see the crate docs). pub fn completions( &mut self, handle: &FileHandle, diff --git a/e2e/tests/cursor.rs b/e2e/tests/cursor.rs new file mode 100644 index 0000000000..ae1d284ddb --- /dev/null +++ b/e2e/tests/cursor.rs @@ -0,0 +1,66 @@ +//! Requests use plain LSP cursor positions (between characters), the same in the server and +//! in tests. + +use swls_e2e_tests::LspHarness; + +const ONTO: &str = "@prefix ex: .\n\ + @prefix rdf: .\n\ + @prefix rdfs: .\n\ + @prefix owl: .\n\ + ex:Car a owl:Class .\n\ + ex:size a rdf:Property ; rdfs:comment \"The size.\" .\n\ + ex:wheels a rdf:Property ; rdfs:domain ex:Car ."; + +fn harness() -> LspHarness { + let mut h = LspHarness::new(); + h.open_linked_file("file:///onto.ttl", "turtle", ONTO); + h.drain_tasks(); + h +} + +#[test_log::test] +fn completing_a_word_right_before_a_semicolon() { + let mut h = harness(); + // Cursor right after `ex:si`, directly followed by `;`. + let src = "@prefix ex: .\n ex:si; ex:size 1 ."; + let file = h.open_file_and_drain("file:///data.ttl", "turtle", src); + let items = h.completions(&file, 1, 9); + let size = items + .iter() + .find(|c| c.label == "ex:size") + .expect("ex:size is offered"); + // It replaces the typed word, not the `;`. + assert_eq!(size.edits[0].range.start.character, 4); + assert_eq!(size.edits[0].range.end.character, 9); +} + +#[test_log::test] +fn hover_on_the_first_character_of_a_term() { + let mut h = harness(); + let src = "@prefix ex: .\n ex:size 1 ."; + let file = h.open_file_and_drain("file:///data.ttl", "turtle", src); + // Column 4 is the `e` of `ex:size`; the character before it is a space. + let hover = h.hover(&file, 1, 4).join("\n"); + assert!(hover.contains("The size."), "{hover}"); +} + +#[test_log::test] +fn property_completion_inside_a_blank_node() { + let mut h = harness(); + let src = "@prefix ex: .\n ex:part [ a ex:Car ;\n \n] ."; + let file = h.open_file_and_drain("file:///data.ttl", "turtle", src); + let items = h.completions(&file, 2, 4); + let wheels = items + .iter() + .find(|c| c.label == "ex:wheels") + .expect("ex:wheels is offered for the blank node"); + // Its domain matches the blank node's type. + assert_eq!( + wheels.kind, + swls_core::lsp_types::CompletionItemKind::FIELD, + "{:?}", + wheels.kind + ); + // Inserted at the cursor, the `]` on the next line stays. + assert_eq!(wheels.edits[0].range.start, wheels.edits[0].range.end); +} From 7362f15e94a8b23f6415dab7dff50afcf2d1f9eb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:32:38 +0000 Subject: [PATCH 09/10] refactor: name type hierarchy walks by what they return `TypeHierarchy::iter_subclass` walked a class's *superclasses* and `iter_superclass` its *subclasses* (the `subclass` field held a class's parents). The outputs were labelled correctly, but only because every caller knew the names were swapped. - Fields `parents` / `children`; `iter_ancestors(_ids)` (the class and its superclasses) and `iter_descendants(_ids)` (the class and its subclasses), sharing one breadth-first `walk`. - The old names stay as deprecated aliases, since `swls-core` is published. - Callers and their variables are renamed to match (`refinements` in class completion, `ancestors` in property and JSON-LD completion), with comments on what each set is used for. Behaviour is unchanged; a unit test pins the direction of both walks. --- core/src/components/type_hierarchy.rs | 135 +++++++++++++++++-------- core/src/systems/properties/systems.rs | 18 ++-- core/src/systems/properties/types.rs | 14 +-- core/src/systems/shapes/model.rs | 4 +- lang-jsonld/src/ecs/completion.rs | 8 +- 5 files changed, 119 insertions(+), 60 deletions(-) diff --git a/core/src/components/type_hierarchy.rs b/core/src/components/type_hierarchy.rs index 0eae6638e8..c11b9e277a 100644 --- a/core/src/components/type_hierarchy.rs +++ b/core/src/components/type_hierarchy.rs @@ -17,8 +17,10 @@ impl Types { for sets in self.0.values_mut() { let new_set = sets .iter() + // Keep only the most specific types: drop a type when one of + // its subclasses is also present. .filter(|&trying| { - for maybe_presnt in hierarchy.iter_superclass_ids(*trying) { + for maybe_presnt in hierarchy.iter_descendant_ids(*trying) { if maybe_presnt == *trying { continue; } @@ -68,15 +70,17 @@ impl Types { pub struct TypeHierarchy { numbers: HashMap, TypeId>, nodes: Vec>, - subclass: Vec>, - superclass: Vec>, + /// Direct superclasses of each class. + parents: Vec>, + /// Direct subclasses of each class. + children: Vec>, } impl TypeHierarchy { /// Number of classes plus subclass edges. Grows whenever the hierarchy /// learns something, so producers can tell whether it changed. pub fn size(&self) -> usize { - self.nodes.len() + self.subclass.iter().map(|s| s.len()).sum::() + self.nodes.len() + self.parents.iter().map(|s| s.len()).sum::() } pub fn get_id(&mut self, class: &str) -> TypeId { @@ -87,8 +91,8 @@ impl TypeHierarchy { let class_cow: Cow<'static, str> = Cow::Owned(class.to_string()); self.nodes.push(class_cow.clone()); self.numbers.insert(class_cow, new_id); - self.subclass.push(HashSet::new()); - self.superclass.push(HashSet::new()); + self.parents.push(HashSet::new()); + self.children.push(HashSet::new()); new_id } } @@ -97,65 +101,114 @@ impl TypeHierarchy { self.numbers.get(class).copied() } - pub fn set_subclass_of(&mut self, class: TypeId, to: TypeId) { - self.subclass[class.0].insert(to); - self.superclass[to.0].insert(class); + /// Record that `class` is a subclass of `of`. + pub fn set_subclass_of(&mut self, class: TypeId, of: TypeId) { + self.parents[class.0].insert(of); + self.children[of.0].insert(class); } - pub fn iter_subclass<'b>(&'b self, id: TypeId) -> impl Iterator> + 'b { - self.iter_subclass_ids(id) + pub fn type_name(&self, id: TypeId) -> Cow<'static, str> { + self.nodes[id.0].clone() + } + + /// `id` and all its superclasses (transitively), by name. + pub fn iter_ancestors<'b>( + &'b self, + id: TypeId, + ) -> impl Iterator> + 'b { + self.iter_ancestor_ids(id) .map(|id| self.nodes[id.0].clone()) } - pub fn iter_subclass_ids<'b>(&'b self, id: TypeId) -> impl Iterator + 'b { - let mut stack = std::collections::VecDeque::new(); - stack.push_back(id); + /// `id` and all its superclasses (transitively). + pub fn iter_ancestor_ids<'b>(&'b self, id: TypeId) -> impl Iterator + 'b { + self.walk(id, &self.parents) + } + + /// `id` and all its subclasses (transitively), by name. + pub fn iter_descendants<'b>( + &'b self, + id: TypeId, + ) -> impl Iterator> + 'b { + self.iter_descendant_ids(id) + .map(|id| self.nodes[id.0].clone()) + } + + /// `id` and all its subclasses (transitively). + pub fn iter_descendant_ids<'b>(&'b self, id: TypeId) -> impl Iterator + 'b { + self.walk(id, &self.children) + } + + /// Breadth-first walk from `id` along `edges`, each class once. + fn walk<'b>( + &'b self, + id: TypeId, + edges: &'b [HashSet], + ) -> impl Iterator + 'b { + let mut queue = std::collections::VecDeque::from([id]); let mut done = HashSet::new(); std::iter::from_fn(move || { - while let Some(id) = stack.pop_front() { - if done.contains(&id) { + while let Some(id) = queue.pop_front() { + if !done.insert(id) { continue; } - done.insert(id); - - self.subclass[id.0].iter().for_each(|i| stack.push_back(*i)); + queue.extend(edges[id.0].iter().copied()); return Some(id); } - None }) } - pub fn type_name(&self, id: TypeId) -> Cow<'static, str> { - self.nodes[id.0].clone() + #[deprecated(note = "walks superclasses; use `iter_ancestors`")] + pub fn iter_subclass<'b>(&'b self, id: TypeId) -> impl Iterator> + 'b { + self.iter_ancestors(id) } + #[deprecated(note = "walks superclasses; use `iter_ancestor_ids`")] + pub fn iter_subclass_ids<'b>(&'b self, id: TypeId) -> impl Iterator + 'b { + self.iter_ancestor_ids(id) + } + + #[deprecated(note = "walks subclasses; use `iter_descendants`")] pub fn iter_superclass<'b>( &'b self, id: TypeId, ) -> impl Iterator> + 'b { - self.iter_superclass_ids(id) - .map(|id| self.nodes[id.0].clone()) + self.iter_descendants(id) } + #[deprecated(note = "walks subclasses; use `iter_descendant_ids`")] pub fn iter_superclass_ids<'b>(&'b self, id: TypeId) -> impl Iterator + 'b { - let mut stack = std::collections::VecDeque::new(); - stack.push_back(id); - let mut done = HashSet::new(); - std::iter::from_fn(move || { - while let Some(id) = stack.pop_front() { - if done.contains(&id) { - continue; - } - done.insert(id); - - self.superclass[id.0] - .iter() - .for_each(|i| stack.push_back(*i)); - return Some(id); - } + self.iter_descendant_ids(id) + } +} - None - }) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ancestors_and_descendants_follow_the_subclass_relation() { + let mut h = TypeHierarchy::default(); + let animal = h.get_id("Animal"); + let dog = h.get_id("Dog"); + let puppy = h.get_id("Puppy"); + h.set_subclass_of(dog, animal); + h.set_subclass_of(puppy, dog); + + let names = |it: &mut dyn Iterator>| { + let mut v: Vec = it.map(|c| c.to_string()).collect(); + v.sort(); + v + }; + assert_eq!( + names(&mut h.iter_ancestors(puppy)), + ["Animal", "Dog", "Puppy"] + ); + assert_eq!( + names(&mut h.iter_descendants(animal)), + ["Animal", "Dog", "Puppy"] + ); + assert_eq!(names(&mut h.iter_ancestors(animal)), ["Animal"]); } } diff --git a/core/src/systems/properties/systems.rs b/core/src/systems/properties/systems.rs index 42bcaa7a61..614ef339c2 100644 --- a/core/src/systems/properties/systems.rs +++ b/core/src/systems/properties/systems.rs @@ -35,10 +35,12 @@ pub fn complete_class( { let tts = types.get(&triple.triple.subject.value); - let superclasses: HashSet<_> = tts + // The subject's inferred types and their subclasses: more specific + // classes are suggested first. + let refinements: HashSet<_> = tts .iter() .flat_map(|x| x.iter()) - .flat_map(|t| hierarchy.iter_superclass(*t)) + .flat_map(|t| hierarchy.iter_descendants(*t)) .collect(); for class in resource.classes.values() { @@ -56,7 +58,7 @@ pub fn complete_class( .label_description(class.full_title()) .documentation(class.full_docs(&hierarchy, prefixes)); - if superclasses.contains(class.term.as_str()) { + if refinements.contains(class.term.as_str()) { completion.kind = CompletionItemKind::INTERFACE; request.push(completion.sort_text(format!("0{}", to_beat))); } else { @@ -133,19 +135,21 @@ pub fn complete_properties( trace!("No types for {}", subject.value); } - let subclasses: HashSet<_> = tts + // The subject's types and their superclasses: a property applies + // when its domain is one of them. + let ancestors: HashSet<_> = tts .iter() .flat_map(|x| x.iter()) - .flat_map(|t| hierarchy.iter_subclass(*t)) + .flat_map(|t| hierarchy.iter_ancestors(*t)) .collect(); for property in resource.properties.values() { let correct_domain = property .domains .iter() - .any(|domain| subclasses.contains(domain.as_str())); + .any(|domain| ancestors.contains(domain.as_str())); - if !subclasses.is_empty() + if !ancestors.is_empty() && config .config .local diff --git a/core/src/systems/properties/types.rs b/core/src/systems/properties/types.rs index 038e6fbfde..87026c31e3 100644 --- a/core/src/systems/properties/types.rs +++ b/core/src/systems/properties/types.rs @@ -38,21 +38,23 @@ impl DefinedClass { } if let Some(id) = hierarchy.get_id_ref(self.term.as_str()) { - let superclasses = group_per_prefix(hierarchy.iter_superclass(id), pref); - if !superclasses.is_empty() { + // "Superclass of" lists the subclasses of this class. + let subclasses = group_per_prefix(hierarchy.iter_descendants(id), pref); + if !subclasses.is_empty() { if !docs.is_empty() { docs += "\n\n" } docs += "**Superclass of:**"; - docs += superclasses.as_str(); + docs += subclasses.as_str(); } - let subclasses = group_per_prefix(hierarchy.iter_subclass(id), pref); - if !subclasses.is_empty() { + // "Subclass of" lists the superclasses of this class. + let superclasses = group_per_prefix(hierarchy.iter_ancestors(id), pref); + if !superclasses.is_empty() { if !docs.is_empty() { docs += "\n\n" } docs += "**Subclass of:**"; - docs += subclasses.as_str(); + docs += superclasses.as_str(); } } diff --git a/core/src/systems/shapes/model.rs b/core/src/systems/shapes/model.rs index 95411699ca..da6e0d3016 100644 --- a/core/src/systems/shapes/model.rs +++ b/core/src/systems/shapes/model.rs @@ -226,9 +226,7 @@ impl<'a> Focus<'a> { if t.subject == *subject && t.predicate.value == RDF_TYPE { classes.insert(t.object.value.to_string()); if let Some(id) = hierarchy.get_id_ref(&t.object.value) { - // `iter_subclass` walks from a class to the classes it is a - // subclass of, i.e. its superclasses. - classes.extend(hierarchy.iter_subclass(id).map(|c| c.to_string())); + classes.extend(hierarchy.iter_ancestors(id).map(|c| c.to_string())); } } } diff --git a/lang-jsonld/src/ecs/completion.rs b/lang-jsonld/src/ecs/completion.rs index 5cd31069fb..7225179a18 100644 --- a/lang-jsonld/src/ecs/completion.rs +++ b/lang-jsonld/src/ecs/completion.rs @@ -388,14 +388,16 @@ pub fn jsonld_property_completion( .filter_map(|(term, def)| def.iri.as_deref().map(|iri| (iri, term.as_str()))) .collect(); - let subclasses: HashSet<_> = type_ids + // The component's types and their superclasses: parameters are + // inherited from superclass components. + let ancestors: HashSet<_> = type_ids .iter() - .flat_map(|t| hierarchy.iter_subclass(*t)) + .flat_map(|t| hierarchy.iter_ancestors(*t)) .collect(); let mut seen_params: HashSet = HashSet::new(); - for type_iri in &subclasses { + for type_iri in &ancestors { let Some(component) = registry.0.components.get(type_iri.as_ref()) else { continue; }; From cbe9b3ace1b0ad0e96c913fcdc225e222910c962 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:41:27 +0000 Subject: [PATCH 10/10] fix: remove a redundant test import flagged by newer clippy Rust 1.100 (CI stable) reports `prelude::*` in the code action tests as unused: `use super::*` already brings the prelude in. Rust 1.97 did not flag it. --- lang-turtle/src/ecs/code_action.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lang-turtle/src/ecs/code_action.rs b/lang-turtle/src/ecs/code_action.rs index c2270e4707..c3af0af9e0 100644 --- a/lang-turtle/src/ecs/code_action.rs +++ b/lang-turtle/src/ecs/code_action.rs @@ -95,7 +95,7 @@ pub fn organize_imports( #[cfg(test)] mod tests { - use swls_core::{feature::code_action::Label as CodeActionLabel, prelude::*}; + use swls_core::feature::code_action::Label as CodeActionLabel; use swls_test_utils::{create_file, setup_world, TestClient}; use super::*;