From f53bf3d823a5554d13fb9f84786783b37486f0d3 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 15 Nov 2026 07:53:42 +0800 Subject: [PATCH 1/3] Own schemas are reached only as package::, parent:: or self:: (#122) Pin core at 14ce546 (import::bare-own-schema-path) and generation and the generators at the CLI's revs. A bare path to one of the package's own schemas is reported with core's own error and fix, from core's check_imports; the "Add use" fix, auto-import and use-path completion write and offer own schemas only as package::. --- Cargo.toml | 8 +- README.md | 16 +- src/analysis/diagnostics.rs | 258 ++++++++++++++++++++++++++-- src/analysis/import_check.rs | 160 ++++++++++++++--- src/analysis/imports.rs | 14 +- src/analysis/project.rs | 8 +- src/analysis/symbols.rs | 4 +- src/handlers/code_actions.rs | 163 +++++++++++++++++- src/handlers/completion/mod.rs | 5 +- src/handlers/completion/tests.rs | 53 +++++- src/handlers/completion/use_path.rs | 81 +++++++-- src/handlers/definition.rs | 22 +-- src/handlers/hovers/ids/tests.rs | 22 +-- src/handlers/references.rs | 2 +- src/handlers/rename.rs | 18 +- 15 files changed, 710 insertions(+), 124 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 55498e9..466226f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -38,14 +38,14 @@ serde_json = "1.0" # Pure Rust, so the analysis library still builds for wasm32. The same # release line `comline-codegen`'s `toml` 0.8 parses with. toml_edit = { version = "0.22", default-features = false, features = ["parse"] } -comline-core = { git = "https://github.com/ComlineProject/core", rev = "868e8310e33df317e3cba4f76b81fbcd8639c1c2" } +comline-core = { git = "https://github.com/ComlineProject/core", rev = "14ce54658455206d639ddc4fbe6d609d20292587" } # What each generator supports, feature by feature (`comline_codegen::features`) # - for warning at a use a declared language can't generate. Only the # generators' `SUPPORT` tables are read; nothing is generated. Pinned to the # same commits as the CLI, so a build has one `comline-codegen`. -comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "922847b608764687b9d75020ff46a3f24d43b5bd" } -comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "ac7fd8b3deaa334d353485414264eb9336500bb9" } -comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "4db92c26b00211aabf90e4ef1b2f55977274d761" } +comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "e22109e1a6ca3c8e5a63338e2fe9acda44123ee1" } +comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "2d2c8853727929a7b350b3017c9ff86cb2ec8911" } +comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "c44b39d68035bd968cec0cd75afb6c6230c4ab76" } # `server`-only. tower-lsp = { version = "0.20.0", optional = true } diff --git a/README.md b/README.md index ab69109..238da53 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ A Language Server Protocol (LSP) implementation for [Comline](https://github.com ### ✅ Fully Implemented -- **Diagnostics** - Real-time syntax errors plus `comline-core`'s validation pass (undefined types, duplicate declarations, ...) — the same checks `comline build` runs. A type from another file of the package used without a `use` gets a specific error with an **"Add `use ...`" quick fix** +- **Diagnostics** - Real-time syntax errors plus `comline-core`'s validation pass (undefined types, duplicate declarations, ...) — the same checks `comline build` runs. A type from another file of the package used without a `use` gets a specific error with an **"Add `use ...`" quick fix**; a `use` that reaches one of the package's own schemas by a bare path (`use types::User` instead of `use package::types::User`) is an error with a **"Write `package::…`" quick fix** - **Whole-package analysis** - every `.ids` file in a package's `src/` takes part, open or not, kept current through file watching; each package only sees its own files - **Dependency packages** - the dependencies `config.idp` declares are indexed (path dependencies, and git pins `comline check` has fetched; the editor never fetches), so imports, hover, go-to-definition and completion work into them under the dependency's name. Unresolved imports are errors, worded like `comline check`'s, with a "did you mean" quick fix; imports of a dependency that isn't fetched yet are marked as not checked, and its `config.idp` entry says why. A dependency whose `@unverified` protocols aren't accepted is an error on its entry, with a quick fix that writes the `accept_unverified` line `comline deps accept` would - **Standard library** - `use std::…` resolves against the std embedded in `comline-core`, like a read-only dependency: hover, go-to-definition (into virtual `comline-std:` documents, whose text clients fetch with the `comline/stdSource` request), completion, and unresolved-import errors worded like `comline check`'s (`std has no schema matching 'std::htp::Request' - did you mean 'std::http'?`) @@ -232,12 +232,20 @@ A `use` path completes one segment at a time, resolved the way `comline check` resolves it: ```comline -use // → the package's namespaces, its dependencies, self / parent / package, std +use // → its dependencies, self / parent / package, std +use package:: // → the package's own schemas use shared:: // → what's under the `shared` dependency -use api::common:: // → what `api::common` declares, then `*` and `{…}` -use api::common::{Error, // → what `api::common` declares that isn't listed yet +use package::api::common:: // → what `api::common` declares, then `*` and `{…}` +use package::api::common::{Error, // → what `api::common` declares that isn't listed yet ``` +The package's own schemas are reached only as `package::…`, `parent::…` or +`self::…`, so they are offered under those and not at the top. A bare path to +one of them (`use types::User`) is the error `import::bare-own-schema-path`, +the same one `comline check` reports, and its quick fix writes `package::` in +front. The "Add `use …`" fix and a type's auto-import write `package::…` for the +package's own schemas, and a dependency's or `std`'s path as it is. + A dependency that isn't fetched yet is offered, marked as such, with nothing under it until `comline check` fetches it. diff --git a/src/analysis/diagnostics.rs b/src/analysis/diagnostics.rs index f08b425..d31f132 100644 --- a/src/analysis/diagnostics.rs +++ b/src/analysis/diagnostics.rs @@ -649,6 +649,9 @@ pub fn project_diagnostics(project: &Project, doc: usize) -> Vec { .iter() .map(|m| missing_import_diagnostic(here.source, m)), ); + // Core's own error for a bare path to one of the package's schemas, with + // its fix (`package::` written in front), carried to the quick fix. + diagnostics.extend(check.bare_own.iter().map(|d| from_core(here.source, d))); diagnostics.extend( check .unresolved @@ -1551,7 +1554,7 @@ struct User { ); let messages = |call: &str| -> Vec { let api = format!( - "use rules::AtLeast\n\nstruct S {{\n @validators = [{call}]\n n: u32\n}}\n" + "use package::rules::AtLeast\n\nstruct S {{\n @validators = [{call}]\n n: u32\n}}\n" ); project_messages(&[("file:///pkg/src/api.ids", &api), rules]) .into_iter() @@ -1589,7 +1592,7 @@ struct User { validator NonEmpty for string {\n validate {\n assert(value.length > 0, f\"{value.name} is empty\")\n }\n}\n", ); let bad = project_messages(&[ - ("file:///pkg/src/api.ids", "use rules::{Count, NonEmpty}\n\nstruct S {\n @validators = [NonEmpty()]\n n: Count\n}\n"), + ("file:///pkg/src/api.ids", "use package::rules::{Count, NonEmpty}\n\nstruct S {\n @validators = [NonEmpty()]\n n: Count\n}\n"), RULES, ]); assert_eq!(bad.len(), 1, "{bad:?}"); @@ -1605,7 +1608,7 @@ struct User { ); let ok = project_messages(&[ - ("file:///pkg/src/api.ids", "use rules::{Name, NonEmpty}\n\nstruct S {\n @validators = [NonEmpty()]\n n: Name\n}\n"), + ("file:///pkg/src/api.ids", "use package::rules::{Name, NonEmpty}\n\nstruct S {\n @validators = [NonEmpty()]\n n: Name\n}\n"), RULES, ]); assert!(ok.is_empty(), "{ok:?}"); @@ -1647,7 +1650,7 @@ struct User { fn an_array_of_an_imported_dataless_type_is_an_error() { const API: (&str, &str) = ( "file:///pkg/src/api.ids", - "use shapes::Empty\n\nstruct Batch {\n items: Empty[]\n}\n", + "use package::shapes::Empty\n\nstruct Batch {\n items: Empty[]\n}\n", ); let messages = |shapes: &str, more: &str| { project_messages(&[ @@ -1662,14 +1665,14 @@ struct User { assert_eq!( dataless(&bad), ["an array of `Empty` carries only its length: `Empty` has no data, so each element \ - would take no bytes — Struct 'Batch', field 'items' — give `Empty` a field, or use a \ + would take no bytes — Struct 'Batch', field 'items' — give `Empty` a field, or use package::a \ count (`u32`) instead"] ); assert_eq!((bad[0].2, bad[0].3), (3, 4), "at the field"); // Through an alias and on into a third file. let through = messages( - "use more::Nothing\n\ntype Empty = Nothing[2]\n", + "use package::more::Nothing\n\ntype Empty = Nothing[2]\n", "struct Nothing {\n unit: ()\n}\n", ); assert_eq!(dataless(&through).len(), 1, "{through:?}"); @@ -1678,7 +1681,7 @@ struct User { // third file's type, a dynamic array. assert!(messages("struct Empty {\n note?: ()\n}\n", "").is_empty()); assert!(messages( - "use more::Nothing\n\nstruct Empty {\n n: Nothing\n}\n", + "use package::more::Nothing\n\nstruct Empty {\n n: Nothing\n}\n", "struct Nothing {\n n: u8\n}\n" ) .is_empty()); @@ -1709,7 +1712,7 @@ struct User { let messages = project_messages(&[ ( "file:///pkg/src/api.ids", - "use shapes::Empty\n\nstruct Batch {\n items: Empty[]\n}\n", + "use package::shapes::Empty\n\nstruct Batch {\n items: Empty[]\n}\n", ), ( "file:///pkg/src/shapes.ids", @@ -1743,14 +1746,14 @@ struct User { .collect(); assert_eq!( messages, - ["`Bounds` is declared in `rules.ids` but not imported here — add `use rules::Bounds`"] + ["`Bounds` is declared in `rules.ids` but not imported here — add `use package::rules::Bounds`"] ); // Imported, it's found - and then its target is what's wrong. let messages: Vec = project_messages(&[ ( "file:///pkg/src/api.ids", - "use rules::Bounds\n\n@validators = [Bounds()]\ntype FixedNum = u8[2]\n", + "use package::rules::Bounds\n\n@validators = [Bounds()]\ntype FixedNum = u8[2]\n", ), BOUNDS, ]) @@ -1827,10 +1830,10 @@ struct User { fn use_forms_core_cannot_expand_alone_are_not_unknown_types() { // Each of these was reported as "Unknown type 'Message'" on its own. for source in [ - "use types::*\n\nstruct S {\n m: Message\n}\n", - "use types::{Message, Other}\n\nstruct S {\n m: Message\n}\n", - "use types\n\nstruct S {\n m: Message\n}\n", - "use types\n\nstruct S {\n m: types::Message\n}\n", + "use package::types::*\n\nstruct S {\n m: Message\n}\n", + "use package::types::{Message, Other}\n\nstruct S {\n m: Message\n}\n", + "use package::types\n\nstruct S {\n m: Message\n}\n", + "use package::types\n\nstruct S {\n m: types::Message\n}\n", ] { assert_eq!(messages(source), Vec::::new(), "{source}"); } @@ -1877,7 +1880,7 @@ struct User { assert_eq!( found, vec![( - "`Message` is declared in `types.ids` but not imported here — add `use types::Message`".to_string(), + "`Message` is declared in `types.ids` but not imported here — add `use package::types::Message`".to_string(), Some(NumberOrString::String(MISSING_IMPORT.to_string())), 1, 7 @@ -1887,7 +1890,7 @@ struct User { #[test] fn a_glob_of_a_project_file_is_expanded_with_what_it_declares() { - let chat = "use types::*\n\nstruct S {\n m: Message\n n: Nope\n}\n"; + let chat = "use package::types::*\n\nstruct S {\n m: Message\n n: Nope\n}\n"; let found = project_messages(&[("file:///pkg/src/chat.ids", chat), TYPES]); assert_eq!(found.len(), 1, "{found:?}"); assert!(found[0].0.starts_with("Unknown type 'Nope'"), "{found:?}"); @@ -1895,12 +1898,12 @@ struct User { #[test] fn using_the_real_name_of_an_aliased_import_says_so() { - let chat = "use types::Message as Msg\n\nstruct S {\n m: Message\n}\n"; + let chat = "use package::types::Message as Msg\n\nstruct S {\n m: Message\n}\n"; let found = project_messages(&[("file:///pkg/src/chat.ids", chat), TYPES]); assert_eq!(found.len(), 1, "{found:?}"); assert_eq!( found[0].0, - "`Message` is imported here as `Msg` — write `Msg`, or add `use types::Message`" + "`Message` is imported here as `Msg` — write `Msg`, or add `use package::types::Message`" ); } @@ -2583,7 +2586,7 @@ mod unverified_judgement_tests { let chat_uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); // Marked: it gives bounded size up, so the marker isn't for nothing. - let marked = "use models::Note\n\n@unverified = \"notes are free text\"\n\ + let marked = "use package::models::Note\n\n@unverified = \"notes are free text\"\n\ protocol Chat {\n function post(note: Note);\n}\n"; let found = found(&files(marked), &chat_uri); assert!(!nothing_given_up(&found), "{found:?}"); @@ -2733,3 +2736,220 @@ mod unverified_judgement_tests { assert!(nothing_given_up(&package(ALLOWS, chat))); } } + +/// A `use` that reaches one of the package's own schemas by a bare path is +/// core's error `import::bare-own-schema-path` (ComlineProject/language-server#122, +/// core#282), with core's fix: `package::` written in front of the path. +#[cfg(test)] +mod bare_own_path_tests { + use super::*; + use lsp_types::NumberOrString; + use crate::analysis::source::SourceFile; + use crate::util::position_to_offset; + use comline_core::schema::ir::compiler::import_resolver::BARE_OWN_SCHEMA_PATH; + + const MANIFEST: &str = "congregation pkg\nspecification_version = 1\n\n\ + dependencies = {\n shared = {\n path = \"../shared\"\n }\n}\n"; + + fn local(path: &str, text: &str) -> SourceFile { + SourceFile::local( + Url::parse(&format!("file:///pkg/{path}")).unwrap(), + text.to_string(), + ) + } + + /// The package: manifest, `types`, `api::common`, a `shared` dependency, + /// and the file under test, `src/chat.ids`. + fn package(chat: &str) -> Vec { + vec![ + local("config.idp", MANIFEST), + local("src/chat.ids", chat), + local( + "src/types.ids", + "struct Message {\n text: string\n}\n\nenum Kind {\n A\n}\n", + ), + local("src/api/common.ids", "struct Error {\n code: u32\n}\n"), + SourceFile::of_dependency( + Url::parse("file:///shared/src/models.ids").unwrap(), + "struct Thing {\n id: u64\n}\n".to_string(), + "shared", + vec!["shared".to_string(), "models".to_string()], + ), + ] + } + + fn diagnostics_of(files: &[SourceFile]) -> Vec { + let project = Project::new(files); + let doc = project.index_of(&files[1].uri).expect("chat.ids parses"); + project_diagnostics(&project, doc) + } + + fn is_bare(d: &Diagnostic) -> bool { + d.code == Some(NumberOrString::String(BARE_OWN_SCHEMA_PATH.id.to_string())) + } + + /// `source` with the diagnostic's quick fix applied. + fn fixed(source: &str, d: &Diagnostic) -> String { + let edits: Vec = + serde_json::from_value(d.data.as_ref().unwrap()[FIX_DATA]["edits"].clone()).unwrap(); + assert_eq!(edits.len(), 1, "{edits:?}"); + let at = position_to_offset(source, edits[0].range.start).unwrap(); + assert_eq!(edits[0].range.start, edits[0].range.end, "an insertion"); + format!("{}{}{}", &source[..at], edits[0].new_text, &source[at..]) + } + + #[test] + fn the_code_is_the_one_core_exports() { + assert_eq!(BARE_OWN_SCHEMA_PATH.id, "import::bare-own-schema-path"); + } + + #[test] + fn a_bare_path_to_an_own_schema_is_core_s_error_worded_as_core_words_it() { + let chat = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let found = diagnostics_of(&package(chat)); + assert_eq!(found.len(), 1, "{found:#?}"); + let d = &found[0]; + assert!(is_bare(d), "{d:?}"); + assert_eq!(d.severity, Some(DiagnosticSeverity::ERROR)); + assert_eq!( + d.message, + "'types::Message' is one of this package's own schemas, reached by a bare path \ + — write `package::types::Message`: a package's own schemas are reached as \ + `package::...`, `parent::...` or `self::...`" + ); + assert_eq!( + (d.range.start.line, d.range.start.character, d.range.end.line), + (0, 0, 0), + "the `use` declaration" + ); + assert_eq!(fix_of(d)["title"], "Write `package::types::Message`"); + } + + fn fix_of(d: &Diagnostic) -> &serde_json::Value { + &d.data.as_ref().expect("data")[FIX_DATA] + } + + /// Every form of a `use`: the error, and the fix makes it go away. + #[test] + fn every_form_is_an_error_and_its_fix_clears_it() { + for header in [ + "use types::Message", + "use types::Message as M", + "use types", + "use types::*", + "use types::{Message, Kind}", + "use api::common::Error", + ] { + let chat = format!("{header}\n\nstruct S {{\n id: u64\n}}\n"); + let found = diagnostics_of(&package(&chat)); + let bare: Vec<_> = found.iter().filter(|d| is_bare(d)).collect(); + assert_eq!(bare.len(), 1, "`{header}`: {found:#?}"); + assert_eq!(found.len(), 1, "nothing else is said of `{header}`: {found:#?}"); + + let repaired = fixed(&chat, bare[0]); + assert_eq!(repaired, chat.replacen("use ", "use package::", 1), "`{header}`"); + let after = diagnostics_of(&package(&repaired)); + assert!(after.is_empty(), "`{header}` fixed: {after:#?}"); + } + } + + #[test] + fn a_bare_path_into_a_nested_directory_gets_the_fix_too() { + let chat = "use api::common::Error\n\nstruct S {\n e: Error\n}\n"; + let found = diagnostics_of(&package(chat)); + assert_eq!(fix_of(&found[0])["title"], "Write `package::api::common::Error`"); + } + + #[test] + fn a_bare_path_is_an_error_without_a_manifest_too() { + let files = vec![ + local("src/chat.ids", "use types::Message\n\nstruct S {\n m: Message\n}\n"), + local("src/types.ids", "struct Message {\n text: string\n}\n"), + ]; + let project = Project::new(&files); + let found = project_diagnostics(&project, 0); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(is_bare(&found[0]), "{found:#?}"); + } + + /// Core stops at the bare path: a name the schema doesn't declare is said + /// once the path is written right. + #[test] + fn a_bare_path_to_a_missing_item_is_only_the_bare_error() { + let chat = "use types::Nope\n\nstruct S {\n id: u64\n}\n"; + let found = diagnostics_of(&package(chat)); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(is_bare(&found[0]), "{found:#?}"); + + let after = diagnostics_of(&package(&fixed(chat, &found[0]))); + assert_eq!(after.len(), 1, "{after:#?}"); + assert_eq!( + after[0].code, + Some(NumberOrString::String(UNRESOLVED_IMPORT.to_string())) + ); + } + + #[test] + fn the_prefixes_a_dependency_and_std_are_not_bare() { + for header in [ + "use package::types::Message", + "use package::types::*", + "use shared::models::Thing", + "use std::http::Request", + ] { + let chat = format!("{header}\n\nstruct S {{\n id: u64\n}}\n"); + let mut files = package(&chat); + files.extend(crate::analysis::stdlib::files(&crate::analysis::stdlib::root())); + let found = diagnostics_of(&files); + assert!( + !found.iter().any(is_bare), + "`{header}` is not a bare path to an own schema: {found:#?}" + ); + } + } + + #[test] + fn a_relative_path_is_not_bare() { + let files = vec![ + local("config.idp", MANIFEST), + local( + "src/api/chat.ids", + "use parent::common::Error\nuse self::inner::Deep\n\nstruct S {\n e: Error\n d: Deep\n}\n", + ), + local("src/api/common.ids", "struct Error {\n code: u32\n}\n"), + local("src/api/chat/inner.ids", "struct Deep {\n n: u8\n}\n"), + ]; + let project = Project::new(&files); + let found = project_diagnostics(&project, 0); + assert!(!found.iter().any(is_bare), "{found:#?}"); + } + + /// A typo reaches nothing: `import::unresolved`, with its "did you mean". + #[test] + fn a_path_that_reaches_nothing_is_unresolved_not_bare() { + let chat = "use typse::Message\n\nstruct S {\n id: u64\n}\n"; + let found = diagnostics_of(&package(chat)); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!( + found[0].code, + Some(NumberOrString::String(UNRESOLVED_IMPORT.to_string())) + ); + } + + /// A dependency's own schemas are written against their own package: a + /// bare path there is not this package's to report. + #[test] + fn a_dependencys_own_files_are_not_checked() { + let mut files = package("struct S {\n id: u64\n}\n"); + files.push(SourceFile::of_dependency( + Url::parse("file:///shared/src/other.ids").unwrap(), + "use models::Thing\n\nstruct Holder {\n t: Thing\n}\n".to_string(), + "shared", + vec!["shared".to_string(), "other".to_string()], + )); + let project = Project::new(&files); + let doc = project.docs.len() - 1; + let found = project_diagnostics(&project, doc); + assert!(!found.iter().any(is_bare), "{found:#?}"); + } +} diff --git a/src/analysis/import_check.rs b/src/analysis/import_check.rs index e82bb1c..67bdcf2 100644 --- a/src/analysis/import_check.rs +++ b/src/analysis/import_check.rs @@ -20,8 +20,11 @@ use std::collections::{BTreeMap, BTreeSet, HashMap}; +use comline_core::diagnostics::Diagnostic as CoreDiagnostic; use comline_core::schema::idl::grammar::Declaration; -use comline_core::schema::ir::compiler::import_resolver::ImportResolver; +use comline_core::schema::ir::compiler::import_resolver::{ + absolute_first_segment, check_imports, ImportResolver, BARE_OWN_SCHEMA_PATH, +}; use comline_core::schema::ir::frozen::unit::FrozenUnit; use lsp_types::SymbolKind; @@ -45,6 +48,10 @@ pub struct ImportCheck { /// Each `use` of a declared dependency there are no files for, so it /// can't be checked here. pub unverified: Vec, + /// Each `use` that reaches one of the package's own schemas by a bare path + /// (`use types::User`, for `use types::User`): core's own error + /// for it, with its fix - see [`bare_own_schema_paths`]. + pub bare_own: Vec, } /// A `use` that doesn't resolve, the way core's `check_imports` sees it. @@ -83,14 +90,19 @@ pub struct MissingImport { /// A project file a missing name could be imported from. pub struct Candidate { pub namespace: Vec, + /// Whether the file is one of the package's own. Its schemas are reached + /// as `package::...`; a dependency's and `std`'s by their own names. + pub own: bool, /// The file's name, for messages (`types.ids`). pub file: String, } impl Candidate { - /// The path a `use` for `name` from this file would take: `types::User`. + /// The path a `use` for `name` from this file would take: + /// `package::types::User` for the package's own schema, `shared::models::Thing` + /// for a dependency's. pub fn use_path(&self, name: &str) -> String { - qualified(&self.namespace, name) + use_path(self.own, &self.namespace, name) } } @@ -212,6 +224,7 @@ pub fn check(project: &Project, doc: usize) -> ImportCheck { .filter(|(i, d)| *i != doc && declares(d, name)) .map(|(_, d)| Candidate { namespace: d.namespace.clone(), + own: d.dependency.is_none(), file: file_name(d), }) .collect(); @@ -234,12 +247,14 @@ pub fn check(project: &Project, doc: usize) -> ImportCheck { } } - let (unresolved, unverified) = resolution(project, doc); + let bare_own = bare_own_schema_paths(project, doc); + let (unresolved, unverified) = resolution(project, doc, &bare_own); ImportCheck { scope, missing, unresolved, unverified, + bare_own, } } @@ -254,7 +269,11 @@ pub fn check(project: &Project, doc: usize) -> ImportCheck { /// Only with the package's `config.idp` in the project: without it, the /// files at hand may not be the whole package (a single file in the /// playground), and nothing could be called unresolved. -fn resolution(project: &Project, doc: usize) -> (Vec, Vec) { +fn resolution( + project: &Project, + doc: usize, + bare_own: &[CoreDiagnostic], +) -> (Vec, Vec) { if !project.has_manifest { return (vec![], vec![]); } @@ -285,6 +304,12 @@ fn resolution(project: &Project, doc: usize) -> (Vec, Vec resolved, Err(detail) => { @@ -380,6 +405,88 @@ fn resolution(project: &Project, doc: usize) -> (Vec, Vec Vec { + use comline_core::package::config::idl::grammar as config_grammar; + use comline_core::package::config::ir::context::ProjectContext; + use comline_core::schema::ir::context::SchemaContext; + use comline_core::utils::codemap::CodeMap; + + let here = &project.docs[doc]; + if here.dependency.is_some() { + return vec![]; + } + + let own: Vec<&Vec> = project + .docs + .iter() + .filter(|d| d.dependency.is_none()) + .map(|d| &d.namespace) + .chain(&project.unparsed) + .collect(); + let reaches_own = here.document.0.iter().any(|decl| { + let Declaration::Use(use_stmt) = &decl.value else { + return false; + }; + absolute_first_segment(&use_stmt.path).is_some_and(|first| { + first != stdlib::NAME + && !project.dependencies.iter().any(|d| d.name == first) + && own.iter().any(|namespace| namespace.first().map(String::as_str) == Some(first)) + }) + }); + if !reaches_own { + return vec![]; + } + + let Ok(congregation) = config_grammar::parse("congregation package") else { + return vec![]; + }; + let mut context = ProjectContext::with_config(congregation); + let schema = |namespace: &[String], codemap: CodeMap| { + let schema = SchemaContext::with_declarations(vec![], namespace.to_vec(), codemap); + std::rc::Rc::new(std::cell::RefCell::new(schema)) + }; + let mut codemap = CodeMap::new(); + codemap.insert_file(here.namespace.join("/"), here.source); + context.schema_contexts.push(schema(&here.namespace, codemap)); + let others = project + .docs + .iter() + .enumerate() + .filter(|(i, d)| *i != doc && d.dependency.is_none()) + .map(|(_, d)| &d.namespace) + .chain(&project.unparsed); + for namespace in others { + context.schema_contexts.push(schema(namespace, CodeMap::new())); + } + + let Err(errors) = check_imports(&here.document.0, &here.namespace, &context) else { + return vec![]; + }; + errors + .into_iter() + .filter(|error| error.code == BARE_OWN_SCHEMA_PATH) + .collect() +} + /// A `std::` path no std schema matches, worded like the build's, with the /// closest std namespace (`std::htp` → `std::http`) as the quick fix for the /// two segments written. @@ -552,6 +659,16 @@ pub(crate) fn file_name(doc: &ProjectDoc) -> String { .unwrap_or_else(|| doc.uri.to_string()) } +/// The path of `name` in the schema at `namespace`: written `package::...` +/// for one of the package's own schemas, as its own schemas are reached; a +/// dependency's (and `std`'s) namespace already starts with its name. +pub(crate) fn use_path(own: bool, namespace: &[String], name: &str) -> String { + match own { + true => format!("package::{}", qualified(namespace, name)), + false => qualified(namespace, name), + } +} + fn qualified(namespace: &[String], name: &str) -> String { if namespace.is_empty() { name.to_string() @@ -605,18 +722,17 @@ mod tests { ]); assert_eq!( missing_names(&files, 0), - vec![("Message".into(), vec!["types::Message".into()])] + vec![("Message".into(), vec!["package::types::Message".into()])] ); } #[test] fn every_use_form_that_imports_the_name_counts() { for header in [ - "use types::Message", - "use types::*", - "use types::{Message, Kind}", - "use types", "use package::types::Message", + "use package::types::*", + "use package::types::{Message, Kind}", + "use package::types", "import types::Message", ] { let source = format!("{header}\n\nstruct S {{\n m: Message\n}}\n"); @@ -655,7 +771,7 @@ mod tests { #[test] fn an_alias_binds_only_the_alias() { - let aliased = "use types::Message as Msg\n\nstruct S {\n a: Msg\n b: Message\n}\n"; + let aliased = "use package::types::Message as Msg\n\nstruct S {\n a: Msg\n b: Message\n}\n"; let files = project(&[("file:///pkg/src/chat.ids", aliased), TYPES]); let project = Project::new(files.iter()); @@ -667,7 +783,7 @@ mod tests { #[test] fn a_use_of_something_else_from_the_same_file_does_not_count() { - for header in ["use types::Kind", "use types::{Kind}"] { + for header in ["use package::types::Kind", "use package::types::{Kind}"] { let source = format!("{header}\n\nstruct S {{\n m: Message\n}}\n"); let files = project(&[("file:///pkg/src/chat.ids", &source), TYPES]); assert_eq!( @@ -680,7 +796,7 @@ mod tests { #[test] fn a_glob_or_whole_namespace_use_of_a_file_outside_the_project_gets_the_benefit_of_the_doubt() { - for header in ["use other::*", "use other"] { + for header in ["use package::other::*", "use package::other"] { let source = format!("{header}\n\nstruct S {{\n m: Message\n}}\n"); let files = project(&[("file:///pkg/src/chat.ids", &source), TYPES]); assert_eq!( @@ -696,7 +812,7 @@ mod tests { let files = project(&[ ( "file:///pkg/src/chat.ids", - "use other::*\n\nstruct S {\n m: Message\n}\n", + "use package::other::*\n\nstruct S {\n m: Message\n}\n", ), ( "file:///pkg/src/other.ids", @@ -706,7 +822,7 @@ mod tests { ]); assert_eq!( missing_names(&files, 0), - vec![("Message".into(), vec!["types::Message".into()])] + vec![("Message".into(), vec!["package::types::Message".into()])] ); } @@ -740,8 +856,8 @@ mod tests { assert_eq!( found[0].1, vec![ - "types::Message".to_string(), - "legacy::types::Message".to_string() + "package::types::Message".to_string(), + "package::legacy::types::Message".to_string() ] ); } @@ -840,7 +956,7 @@ mod tests { #[test] fn an_item_the_schema_does_not_declare_is_unresolved() { let (unresolved, _) = - resolution_of("use types::{User, Usr}\n\nstruct S {\n u: User\n}\n"); + resolution_of("use package::types::{User, Usr}\n\nstruct S {\n u: User\n}\n"); assert_eq!( unresolved, vec![( @@ -854,12 +970,12 @@ mod tests { #[test] fn imports_that_resolve_or_cannot_be_checked_are_not_unresolved() { for body in [ - "use types::User\n\nstruct S {\n u: User\n}\n", - "use types::Gone\n\nstruct S {\n id: u64\n}\n", - "use types\n\nstruct S {\n u: User\n}\n", + "use package::types::User\n\nstruct S {\n u: User\n}\n", + "use package::types::Gone\n\nstruct S {\n id: u64\n}\n", + "use package::types\n\nstruct S {\n u: User\n}\n", "use std::http::{Request, Response}\n\nstruct S {\n r: Request\n}\n", "use std::validators::StringBounds\n\nstruct S {\n id: u64\n}\n", - "use broken::Anything\n\nstruct S {\n id: u64\n}\n", + "use package::broken::Anything\n\nstruct S {\n id: u64\n}\n", "use shared::models::Thing\n\nstruct S {\n t: Thing\n}\n", ] { let (unresolved, unverified) = resolution_of(body); diff --git a/src/analysis/imports.rs b/src/analysis/imports.rs index 72eb064..fce9e3f 100644 --- a/src/analysis/imports.rs +++ b/src/analysis/imports.rs @@ -248,7 +248,7 @@ mod tests { #[test] fn use_with_remaining_symbol_resolves_to_the_namespace_sibling() { - let doc = parse_use("use types::User"); + let doc = parse_use("use package::types::User"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -259,7 +259,7 @@ mod tests { #[test] fn use_of_the_whole_namespace_resolves_any_name_it_declares() { - let doc = parse_use("use types"); + let doc = parse_use("use package::types"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -268,7 +268,7 @@ mod tests { #[test] fn use_glob_resolves_any_name() { - let doc = parse_use("use types::*"); + let doc = parse_use("use package::types::*"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -277,7 +277,7 @@ mod tests { #[test] fn use_multi_only_resolves_listed_names() { - let doc = parse_use("use types::{User, Post}"); + let doc = parse_use("use package::types::{User, Post}"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -309,7 +309,7 @@ mod tests { // Matches `use_brings_into_scope`'s existing, already-shipped rule // (`symbol == name || alias == Some(name)`) - aliasing adds a // binding, it doesn't hide the original name. - let doc = parse_use("use types::User as Account"); + let doc = parse_use("use package::types::User as Account"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -322,7 +322,7 @@ mod tests { // `types.ids`'s own symbol table never heard of "Account" - a // caller that looked it up there by the alias instead of // `real_name` would get nothing. - let doc = parse_use("use types::Message as Msg"); + let doc = parse_use("use package::types::Message as Msg"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["types"])]; @@ -335,7 +335,7 @@ mod tests { // The actual regression this module exists to fix: a flat scan // can't tell these apart and would just return whichever sibling // happened to come first. - let doc = parse_use("use b::Message"); + let doc = parse_use("use package::b::Message"); let imports = resolved_imports(&doc, &["app".to_string()]); let siblings = vec![file(&["a"]), file(&["b"])]; diff --git a/src/analysis/project.rs b/src/analysis/project.rs index 3c6504d..2138666 100644 --- a/src/analysis/project.rs +++ b/src/analysis/project.rs @@ -798,8 +798,8 @@ mod tests { let all = files(&[ ("file:///types.ids", "struct Message {\n text: string\n}\n"), ("file:///other.ids", "struct Message {\n other: bool\n}\n"), - ("file:///chat.ids", "use types::Message\n\nprotocol Chat {\n function send(Message) -> Message;\n}\n"), - ("file:///unrelated.ids", "use other::Message\n\nstruct S {\n m: Message\n}\n"), + ("file:///chat.ids", "use package::types::Message\n\nprotocol Chat {\n function send(Message) -> Message;\n}\n"), + ("file:///unrelated.ids", "use package::other::Message\n\nstruct S {\n m: Message\n}\n"), ]); let project = Project::new(all.iter()); let target = project @@ -827,7 +827,7 @@ mod tests { ), ( "file:///chat.ids", - "use types::Message as Msg\n\nstruct S {\n m: Msg\n}\n", + "use package::types::Message as Msg\n\nstruct S {\n m: Msg\n}\n", ), ]); let project = Project::new(all.iter()); @@ -875,7 +875,7 @@ mod tests { fn a_local_declaration_shadows_an_import() { let all = files(&[ ("file:///types.ids", "struct Message {\n text: string\n}\n"), - ("file:///chat.ids", "use types::Message\n\nstruct Message {\n local: bool\n}\n\nstruct S {\n m: Message\n}\n"), + ("file:///chat.ids", "use package::types::Message\n\nstruct Message {\n local: bool\n}\n\nstruct S {\n m: Message\n}\n"), ]); let project = Project::new(all.iter()); let target = project diff --git a/src/analysis/symbols.rs b/src/analysis/symbols.rs index cfaa94f..40c68f8 100644 --- a/src/analysis/symbols.rs +++ b/src/analysis/symbols.rs @@ -466,7 +466,7 @@ protocol UserService { // Every other position a name appears in. ("f: Test", Namespace::Declaration), ("function f() ! Test;", Namespace::Declaration), - ("use types::Test", Namespace::Declaration), + ("use package::types::Test", Namespace::Declaration), ("@deprecated = Test", Namespace::Declaration), ]; for (source, expected) in cases { @@ -479,7 +479,7 @@ protocol UserService { fn declaration_range_is_the_declared_name_not_an_earlier_substring() { // `User` appears first inside `UserProfile`, then in the `use` // line, then in a docstring - none of them are the declaration. - let source = "use types::User\n\nstruct UserProfile {\n id: u64\n}\n\n/// The User record\nstruct User {\n name: string\n}\n"; + let source = "use package::types::User\n\nstruct UserProfile {\n id: u64\n}\n\n/// The User record\nstruct User {\n name: string\n}\n"; let uri = Url::parse("file:///test.ids").unwrap(); let result = parser::parse(source).unwrap(); diff --git a/src/handlers/code_actions.rs b/src/handlers/code_actions.rs index e71c0e2..6ee4132 100644 --- a/src/handlers/code_actions.rs +++ b/src/handlers/code_actions.rs @@ -416,7 +416,7 @@ mod tests { #[test] fn a_missing_import_gets_an_add_use_fix() { - let chat = "use other::Thing\n\nstruct S {\n m: Message\n}\n"; + let chat = "use package::other::Thing\n\nstruct S {\n m: Message\n}\n"; let chat_uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); let others = [( Url::parse("file:///pkg/src/types.ids").unwrap(), @@ -429,8 +429,8 @@ mod tests { assert_eq!( titles_and_edits(actions), vec![( - "Add `use types::Message`".to_string(), - "use types::Message\n".to_string(), + "Add `use package::types::Message`".to_string(), + "use package::types::Message\n".to_string(), 1 )] ); @@ -532,7 +532,7 @@ mod tests { .collect(); assert_eq!( titles, - vec!["Add `use types::Message`", "Add `use legacy::Message`"] + vec!["Add `use package::types::Message`", "Add `use package::legacy::Message`"] ); } @@ -684,7 +684,7 @@ mod duplicate_name_tests { ), SourceFile::local( Url::parse("file:///pkg/src/other.ids").unwrap(), - "use chat::Test\n\nstruct Holder {\n t: Test\n}\n".to_string(), + "use package::chat::Test\n\nstruct Holder {\n t: Test\n}\n".to_string(), ), ]; let action = actions(THREE_TESTS, &at(0, 8), &others) @@ -927,3 +927,156 @@ mod duplicate_name_tests { } } } + +/// The two sides of the own-schema path rule (ComlineProject/language-server#122): +/// the quick fix for a bare path, and the "Add `use ...`" fix writing what the +/// rule asks for. +#[cfg(test)] +mod own_schema_path_tests { + use super::*; + use crate::analysis::diagnostics::project_diagnostics; + use crate::analysis::source::SourceFile; + use lsp_types::{CodeActionContext, Position, TextDocumentIdentifier}; + + fn params(uri: &Url, range: Range, diagnostics: Vec) -> CodeActionParams { + CodeActionParams { + text_document: TextDocumentIdentifier { uri: uri.clone() }, + range, + context: CodeActionContext { + diagnostics, + only: None, + trigger_kind: None, + }, + work_done_progress_params: Default::default(), + partial_result_params: Default::default(), + } + } + + fn actions_of(actions: Vec) -> Vec { + actions + .into_iter() + .map(|a| match a { + CodeActionOrCommand::CodeAction(a) => a, + other => panic!("expected a code action, got {other:?}"), + }) + .collect() + } + + fn local(path: &str, text: &str) -> SourceFile { + SourceFile::local( + Url::parse(&format!("file:///pkg/{path}")).unwrap(), + text.to_string(), + ) + } + + /// The edits `action` makes to `uri`, applied to `source`. + fn apply(source: &str, uri: &Url, action: &CodeAction) -> String { + let changes = action.edit.as_ref().unwrap().changes.as_ref().unwrap(); + let mut edits = changes[uri].clone(); + edits.sort_by_key(|e| std::cmp::Reverse((e.range.start.line, e.range.start.character))); + let mut out = source.to_string(); + for edit in edits { + let start = crate::util::position_to_offset(&out, edit.range.start).unwrap(); + let end = crate::util::position_to_offset(&out, edit.range.end).unwrap(); + out.replace_range(start..end, &edit.new_text); + } + out + } + + #[test] + fn a_bare_path_to_an_own_schema_gets_a_write_package_fix() { + let chat = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); + let others = [local( + "src/types.ids", + "struct Message {\n text: string\n}\n", + )]; + + let diagnostics = { + let mut all = vec![SourceFile::local(uri.clone(), chat.to_string())]; + all.extend(others.iter().cloned()); + let project = Project::new(&all); + project_diagnostics(&project, 0) + }; + assert_eq!(diagnostics.len(), 1, "{diagnostics:#?}"); + + let cursor = Range::new(Position::new(0, 6), Position::new(0, 6)); + let fixes = actions_of(get_code_actions_with_project( + chat, + &uri, + ¶ms(&uri, cursor, diagnostics.clone()), + &others, + )); + assert_eq!(fixes.len(), 1, "{fixes:#?}"); + let fix = &fixes[0]; + assert_eq!(fix.title, "Write `package::types::Message`"); + assert_eq!(fix.kind, Some(CodeActionKind::QUICKFIX)); + assert_eq!(fix.is_preferred, Some(true)); + assert_eq!(fix.diagnostics.as_deref(), Some(&diagnostics[..])); + assert_eq!( + apply(chat, &uri, fix), + "use package::types::Message\n\nstruct S {\n m: Message\n}\n" + ); + } + + #[test] + fn the_fix_is_not_offered_away_from_the_use() { + let chat = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); + let others = [local( + "src/types.ids", + "struct Message {\n text: string\n}\n", + )]; + let mut all = vec![SourceFile::local(uri.clone(), chat.to_string())]; + all.extend(others.iter().cloned()); + let diagnostics = project_diagnostics(&Project::new(&all), 0); + + let away = Range::new(Position::new(3, 8), Position::new(3, 8)); + let fixes = actions_of(get_code_actions_with_project( + chat, + &uri, + ¶ms(&uri, away, diagnostics), + &others, + )); + assert!(fixes.is_empty(), "{fixes:#?}"); + } + + #[test] + fn add_use_writes_package_for_an_own_schema_and_the_dependencys_own_name_for_a_dependency() { + let chat = "struct S {\n m: Message\n e: Error\n t: Thing\n}\n"; + let uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); + let others = [ + local( + "config.idp", + "congregation app\nspecification_version = 1\n\ndependencies = {\n shared = {\n path = \"../shared\"\n }\n}\n", + ), + local("src/types.ids", "struct Message {\n text: string\n}\n"), + local("src/api/common.ids", "struct Error {\n code: u32\n}\n"), + SourceFile::of_dependency( + Url::parse("file:///shared/src/models.ids").unwrap(), + "struct Thing {\n id: u64\n}\n".to_string(), + "shared", + vec!["shared".to_string(), "models".to_string()], + ), + ]; + + let whole = Range::new(Position::new(0, 0), Position::new(5, 0)); + let titles: Vec = actions_of(get_code_actions_with_project( + chat, + &uri, + ¶ms(&uri, whole, vec![]), + &others, + )) + .into_iter() + .map(|a| a.title) + .collect(); + assert_eq!( + titles, + [ + "Add `use package::types::Message`", + "Add `use package::api::common::Error`", + "Add `use shared::models::Thing`", + ] + ); + } +} diff --git a/src/handlers/completion/mod.rs b/src/handlers/completion/mod.rs index 1165226..fb794b6 100644 --- a/src/handlers/completion/mod.rs +++ b/src/handlers/completion/mod.rs @@ -9,6 +9,7 @@ mod tests; use std::collections::BTreeSet; use crate::analysis::import_check::{self, declares_type, file_name, is_type_kind, Target}; +use crate::analysis::import_check::use_path; use crate::analysis::imports::{self, add_use_edit, ResolvedUse}; use crate::analysis::project::{Project, ProjectDoc}; use crate::analysis::source::ProjectSource; @@ -302,7 +303,9 @@ fn unimported_item( source: &str, item: impl FnOnce(String) -> CompletionItem, ) -> CompletionItem { - let path = format!("{}::{}", doc.namespace.join("::"), name); + // The package's own schemas are reached as `package::...`, a dependency's + // and `std`'s by their own names. + let path = use_path(doc.dependency.is_none(), &doc.namespace, name); let mut item = item(format!("from {} — adds `use {path}`", origin(doc))); item.sort_text = Some(match doc.dependency { Some(_) => format!("~~{name}"), diff --git a/src/handlers/completion/tests.rs b/src/handlers/completion/tests.rs index 9badba5..c4891f3 100644 --- a/src/handlers/completion/tests.rs +++ b/src/handlers/completion/tests.rs @@ -937,15 +937,15 @@ fn imported_items(source: &str) -> Vec<(String, String, Option)> { #[test] fn imported_types_are_offered_and_the_rest_add_their_use() { // Mid-edit: the file doesn't parse, its `use` line still does. - let items = imported_items("use types::Message\n\nstruct S {\n m: "); + let items = imported_items("use package::types::Message\n\nstruct S {\n m: "); assert_eq!( items, vec![ ("Message".to_string(), "from `types.ids`".to_string(), None), ( "Kind".to_string(), - "from `types.ids` — adds `use types::Kind`".to_string(), - Some("use types::Kind\n".to_string()) + "from `types.ids` — adds `use package::types::Kind`".to_string(), + Some("use package::types::Kind\n".to_string()) ), ], "the protocol `Api` isn't a type" @@ -953,7 +953,7 @@ fn imported_types_are_offered_and_the_rest_add_their_use() { } #[test] fn an_alias_is_offered_under_its_alias_only() { - let items = imported_items("use types::Message as Msg\n\nstruct S {\n m: "); + let items = imported_items("use package::types::Message as Msg\n\nstruct S {\n m: "); let labels: Vec<_> = items .iter() .map(|(l, d, _)| (l.as_str(), d.as_str())) @@ -969,7 +969,7 @@ fn an_alias_is_offered_under_its_alias_only() { } #[test] fn a_glob_brings_in_every_type() { - let items = imported_items("use types::*\n\nstruct S {\n m: "); + let items = imported_items("use package::types::*\n\nstruct S {\n m: "); assert_eq!(items.len(), 2, "{items:?}"); assert!(items.iter().all(|(_, _, edit)| edit.is_none()), "{items:?}"); } @@ -978,7 +978,7 @@ fn without_a_use_every_type_adds_one_at_the_top() { let items = imported_items("struct S {\n m: "); assert_eq!(items.len(), 2, "{items:?}"); assert!(items.iter().any( - |(l, _, edit)| l == "Message" && edit.as_deref() == Some("use types::Message\n\n") + |(l, _, edit)| l == "Message" && edit.as_deref() == Some("use package::types::Message\n\n") )); } #[test] @@ -1089,3 +1089,44 @@ fn the_language_deprecates_no_completion_yet() { assert!(!items.is_empty()); assert!(items.iter().all(|i| i.tags.is_none())); } +#[test] +fn an_unimported_own_type_adds_a_package_path_and_a_dependencys_type_its_own_name() { + let uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); + let files = vec![ + crate::analysis::source::SourceFile::local( + Url::parse("file:///pkg/config.idp").unwrap(), + "congregation app\nspecification_version = 1\n\ndependencies = {\n shared = {\n path = \"../shared\"\n }\n}\n".to_string(), + ), + crate::analysis::source::SourceFile::local( + Url::parse("file:///pkg/src/api/common.ids").unwrap(), + "struct Error {\n code: u32\n}\n".to_string(), + ), + crate::analysis::source::SourceFile::of_dependency( + Url::parse("file:///shared/src/models.ids").unwrap(), + "struct Thing {\n id: u64\n}\n".to_string(), + "shared", + vec!["shared".to_string(), "models".to_string()], + ), + ]; + let source = "struct S {\n m: "; + let items = get_completions_with_project(source, &uri, crate::util::offset_to_position(source, source.len()), &files); + let detail = |label: &str| { + items + .iter() + .find(|c| c.label == label) + .and_then(|c| c.detail.clone()) + .unwrap_or_else(|| panic!("no {label}")) + }; + assert_eq!(detail("Error"), "from `common.ids` — adds `use package::api::common::Error`"); + assert_eq!(detail("Thing"), "from `models.ids` (dependency `shared`) — adds `use shared::models::Thing`"); + + let edit = |label: &str| { + items + .iter() + .find(|c| c.label == label) + .and_then(|c| c.additional_text_edits.as_ref()) + .map(|edits| edits[0].new_text.clone()) + }; + assert_eq!(edit("Error").as_deref(), Some("use package::api::common::Error\n\n")); + assert_eq!(edit("Thing").as_deref(), Some("use shared::models::Thing\n\n")); +} diff --git a/src/handlers/completion/use_path.rs b/src/handlers/completion/use_path.rs index 2a8a5d8..9aca53c 100644 --- a/src/handlers/completion/use_path.rs +++ b/src/handlers/completion/use_path.rs @@ -1,6 +1,7 @@ //! Completion inside a `use` path. `use ` offers what a path can start with -//! (the package's namespaces, its dependencies, `self` / `parent` / -//! `package`, `std`), `use shared::` what's under `shared`, and +//! (its dependencies, `self` / `parent` / `package`, `std`: the package's own +//! schemas are reached through the prefixes), `use package::` what's under the +//! package, `use shared::` what's under `shared`, and //! `use shared::models::{Thing, ` the rest of what `shared::models` declares. //! //! A path is resolved the way the build resolves it, relative prefixes @@ -183,6 +184,13 @@ pub(super) fn completions( } let relative = modules::is_relative_prefix(&prefix.segments[0]); + // A bare path to the package's own schemas is an error + // (`import::bare-own-schema-path`), so nothing is offered along it: they + // are reached through `package::`, `parent::` or `self::`. The legacy + // `import` has no such prefixes. + if !prefix.legacy && !relative && !leaves_the_package(&project, &prefix.segments[0]) { + return vec![]; + } let Some(base) = modules::resolve_path(&prefix.segments, prefix.legacy, uri) else { return vec![]; // `parent::` above the top }; @@ -217,13 +225,27 @@ pub(super) fn completions( items } -/// `use ` itself: the package's own top-level namespaces, then its declared -/// dependencies, then `self` / `parent` / `package` and `std`. +/// Whether an absolute path starting with `first` goes into `std` or a +/// dependency, rather than naming one of the package's own schemas. +fn leaves_the_package(project: &Project, first: &str) -> bool { + first == stdlib::NAME + || project.dependencies.iter().any(|d| d.name == first) + || project.docs.iter().any(|d| d.dependency == Some(first)) +} + +/// `use ` itself: the package's declared dependencies, then `self` / `parent` / +/// `package` and `std`. The package's own schemas are not offered here: they +/// are reached through `package::`, `parent::` or `self::`, so a bare one would +/// be an error (`import::bare-own-schema-path`). The legacy `import` has no +/// such prefixes and still lists them. fn path_starts(project: &Project, legacy: bool, range: Range) -> Vec { - let mut items: Vec = modules::children(project, &[], true) - .iter() - .map(|child| sorted(child_item(child, range), '0')) - .collect(); + let mut items: Vec = match legacy { + true => modules::children(project, &[], true) + .iter() + .map(|child| sorted(child_item(child, range), '0')) + .collect(), + false => vec![], + }; for dependency in &project.dependencies { if items.iter().any(|item| item.label == dependency.name) { @@ -557,14 +579,25 @@ mod tests { } #[test] - fn a_path_starts_with_the_packages_namespaces_its_dependencies_and_the_prefixes() { + fn a_path_starts_with_the_dependencies_and_the_prefixes_not_the_packages_own_schemas() { let items = complete("use "); assert_eq!( labels(&items), - ["api", "types", "net", "shared", "package", "parent", "self", "std"] + ["net", "shared", "package", "parent", "self", "std"], + "the package's own schemas are reached through `package::`, not offered bare" ); let find = |label: &str| items.iter().find(|(l, _, _)| l == label).unwrap(); + assert_eq!(find("shared").1, "dependency, path `../shared`"); + assert_eq!(find("net").1, "dependency, git — not fetched yet"); + assert_eq!(find("parent").1, "In a `use` path, one namespace level up."); + } + + #[test] + fn the_packages_own_schemas_are_offered_under_package() { + let items = complete("use package::"); + let find = |label: &str| items.iter().find(|(l, _, _)| l == label).unwrap(); + assert_eq!(labels(&items), ["api", "types"]); assert_eq!( find("api"), &("api".into(), "`api/`".into(), "api::".into()), @@ -575,14 +608,25 @@ mod tests { &("types".into(), "`types.ids`".into(), "types".into()), "a schema can end a path" ); - assert_eq!(find("shared").1, "dependency, path `../shared`"); - assert_eq!(find("net").1, "dependency, git — not fetched yet"); - assert_eq!(find("parent").1, "In a `use` path, one namespace level up."); + } + + #[test] + fn nothing_is_offered_along_a_bare_path_to_an_own_schema() { + for source in ["use api::", "use types::", "use types::{", "use api::common::"] { + assert!( + complete(source).is_empty(), + "`{source}` is `import::bare-own-schema-path`: {:?}", + complete(source) + ); + } + // The same paths, written the way they're reached, are offered. + assert!(!complete("use package::api::").is_empty()); + assert!(!complete("use package::types::").is_empty()); } #[test] fn a_namespace_offers_whats_under_it() { - let items = complete("use api::"); + let items = complete("use package::api::"); assert_eq!( items, [ @@ -594,7 +638,7 @@ mod tests { #[test] fn a_schema_offers_its_declarations_then_glob_and_list() { - let items = complete("use types::"); + let items = complete("use package::types::"); assert_eq!(labels(&items), ["Kind", "NotFound", "User", "*", "{…}"]); assert_eq!(items[1].1, "error", "errors are importable too"); assert_eq!(items[4].2, "{$0}"); @@ -825,7 +869,7 @@ mod tests { #[test] fn a_path_start_carries_each_modules_and_packages_docs() { - let items = documented("use "); + let items = documented("use package::"); assert_eq!( docs_for(&items, "types").as_deref(), Some("The package's types.") @@ -835,6 +879,7 @@ mod tests { None, "a directory with no schema of its own" ); + let items = documented("use "); assert_eq!( docs_for(&items, "shared").as_deref(), Some("A shared package."), @@ -855,7 +900,7 @@ mod tests { .unwrap() .starts_with("Validators to attach to fields")); assert_eq!( - docs_for(&documented("use api::"), "common").as_deref(), + docs_for(&documented("use package::api::"), "common").as_deref(), Some("Things every API schema needs.") ); assert_eq!( @@ -877,7 +922,7 @@ mod tests { Some("A thing.") ); assert_eq!( - docs_for(&documented("use types::{"), "User").as_deref(), + docs_for(&documented("use package::types::{"), "User").as_deref(), Some("Someone."), "in a brace list" ); diff --git a/src/handlers/definition.rs b/src/handlers/definition.rs index 0a8864e..b9c34fb 100644 --- a/src/handlers/definition.rs +++ b/src/handlers/definition.rs @@ -181,7 +181,7 @@ struct User { #[test] fn test_goto_definition_in_another_file_via_use() { let chat_source = - "use types::Message\n\nprotocol Chat {\n function send() -> Message;\n}\n"; + "use package::types::Message\n\nprotocol Chat {\n function send() -> Message;\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let chat_uri = Url::parse("file:///chat.ids").unwrap(); @@ -201,7 +201,7 @@ struct User { #[test] fn test_goto_definition_two_siblings_same_name_picks_the_imported_one() { - let active_source = "use b::Message\n\nprotocol P {\n function f() -> Message;\n}\n"; + let active_source = "use package::b::Message\n\nprotocol P {\n function f() -> Message;\n}\n"; let a_source = "struct Message {\n from_a: bool\n}\n"; let b_source = "struct Message {\n from_b: bool\n}\n"; @@ -226,7 +226,7 @@ struct User { #[test] fn test_goto_definition_through_an_as_alias() { let active_source = - "use types::Message as Msg\n\nprotocol P {\n function f() -> Msg;\n}\n"; + "use package::types::Message as Msg\n\nprotocol P {\n function f() -> Msg;\n}\n"; let types_source = "struct Other {\n x: bool\n}\n\nstruct Message {\n text: string\n}\n"; @@ -249,17 +249,17 @@ struct User { #[test] fn test_goto_definition_from_the_use_line_itself() { - let active_source = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let active_source = "use package::types::Message\n\nstruct S {\n m: Message\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let active_uri = Url::parse("file:///active.ids").unwrap(); let types_uri = Url::parse("file:///types.ids").unwrap(); - // "Message" in `use types::Message` + // "Message" in `use package::types::Message` let location = scalar(find_definition_with_project( active_source, &active_uri, - Position::new(0, 13), + Position::new(0, 22), &[(types_uri.clone(), types_source.to_string())], )); @@ -288,7 +288,7 @@ struct User { #[test] fn test_goto_definition_prefers_a_local_declaration() { - let active_source = "use types::Message\n\nstruct Message {\n local: bool\n}\n\nstruct S {\n m: Message\n}\n"; + let active_source = "use package::types::Message\n\nstruct Message {\n local: bool\n}\n\nstruct S {\n m: Message\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let active_uri = Url::parse("file:///active.ids").unwrap(); @@ -375,7 +375,7 @@ struct User { #[test] fn a_module_segment_jumps_to_its_own_schema_file() { let location = - definition_in("chat.ids", "use types::User\n", "types").expect("module definition"); + definition_in("chat.ids", "use package::types::User\n", "types").expect("module definition"); assert_eq!(location.uri.as_str(), "file:///pkg/src/types.ids"); assert_eq!(location.range.start, Position::new(0, 0)); } @@ -401,7 +401,7 @@ struct User { // `api` has both a schema (`api.ids`) and a deeper module // (`api::common`) - the schema is what a jump lands on. let location = - definition_in("chat.ids", "use api::common::Error\n", "api").expect("api.ids exists"); + definition_in("chat.ids", "use package::api::common::Error\n", "api").expect("api.ids exists"); assert_eq!(location.uri.as_str(), "file:///pkg/src/api.ids"); } @@ -415,7 +415,7 @@ struct User { "struct Profile {\n id: u64\n}\n", )]; let uri = Url::parse("file:///pkg/src/chat.ids").unwrap(); - let source = "use api::v1::user::Profile\n"; + let source = "use package::api::v1::user::Profile\n"; let offset = source.find("v1").unwrap(); let position = crate::util::offset_to_position(source, offset); assert!(find_definition_with_project(source, &uri, position, &files).is_none()); @@ -439,7 +439,7 @@ struct User { #[test] fn a_whole_namespace_import_names_a_module_at_the_end() { let location = - definition_in("chat.ids", "use types\n", "types").expect("lone word on a use line"); + definition_in("chat.ids", "use package::types\n", "types").expect("lone word on a use line"); assert_eq!(location.uri.as_str(), "file:///pkg/src/types.ids"); } diff --git a/src/handlers/hovers/ids/tests.rs b/src/handlers/hovers/ids/tests.rs index a02f336..fb3c55d 100644 --- a/src/handlers/hovers/ids/tests.rs +++ b/src/handlers/hovers/ids/tests.rs @@ -317,7 +317,7 @@ struct User { #[test] fn test_hover_on_struct_declared_in_another_file() { // `chat.ids` references `Message`, declared only in `types.ids`. - let chat_source = r#"use types::Message + let chat_source = r#"use package::types::Message protocol Chat { function send(text: string) -> Message; } @@ -388,7 +388,7 @@ protocol Chat { assert!(!text.contains("packed@1"), "got: {text}"); assert!(!text.contains("json@1"), "got: {text}"); - let text = hover_on("use types::Message\n\nstruct S {\n m: Message\n}\n", 2); + let text = hover_on("use package::types::Message\n\nstruct S {\n m: Message\n}\n", 2); assert!(text.contains("packed@1: 8 B"), "got: {text}"); } @@ -569,7 +569,7 @@ protocol Chat { #[test] fn use_types_message_resolves_silently_no_note() { let chat_source = - "use types::Message\n\nprotocol Chat {\n function send() -> Message;\n}\n"; + "use package::types::Message\n\nprotocol Chat {\n function send() -> Message;\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let chat_uri = Url::parse("file:///chat.ids").unwrap(); @@ -595,8 +595,8 @@ protocol Chat { // The actual bug item 4 of this whole plan exists to fix: a flat, // first-match scan can't tell `a.ids`'s `Message` from `b.ids`'s - // it just returns whichever file happened to come first in - // `other_files`. `use b::Message` must resolve to `b`'s. - let active_source = "use b::Message\n\nprotocol P {\n function f() -> Message;\n}\n"; + // `other_files`. `use package::b::Message` must resolve to `b`'s. + let active_source = "use package::b::Message\n\nprotocol P {\n function f() -> Message;\n}\n"; let a_source = "struct Message {\n from_a: bool\n}\n"; let b_source = "struct Message {\n from_b: bool\n}\n"; @@ -625,7 +625,7 @@ protocol Chat { #[test] fn use_multi_resolves_a_listed_item_silently() { let active_source = - "use types::{Message, Other}\n\nprotocol P {\n function f() -> Message;\n}\n"; + "use package::types::{Message, Other}\n\nprotocol P {\n function f() -> Message;\n}\n"; let types_source = "struct Message {\n text: string\n}\nstruct Other {\n n: u8\n}\n"; let active_uri = Url::parse("file:///active.ids").unwrap(); @@ -646,7 +646,7 @@ protocol Chat { #[test] fn use_glob_resolves_anything_in_the_namespace_silently() { - let active_source = "use types::*\n\nprotocol P {\n function f() -> Message;\n}\n"; + let active_source = "use package::types::*\n\nprotocol P {\n function f() -> Message;\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let active_uri = Url::parse("file:///active.ids").unwrap(); @@ -668,7 +668,7 @@ protocol Chat { #[test] fn use_as_alias_resolves_the_aliased_name_to_the_real_declaration() { let active_source = - "use types::Message as Msg\n\nprotocol P {\n function f() -> Msg;\n}\n"; + "use package::types::Message as Msg\n\nprotocol P {\n function f() -> Msg;\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let active_uri = Url::parse("file:///active.ids").unwrap(); @@ -776,7 +776,7 @@ protocol Chat { #[test] fn a_module_segment_shows_its_docs_and_the_types_it_declares() { - let text = hover_in("chat.ids", "use types::User\n", "types", 1).expect("module hover"); + let text = hover_in("chat.ids", "use package::types::User\n", "types", 1).expect("module hover"); assert!(text.contains("module types"), "{text}"); assert!( text.contains("The package's types.\n\nShared by everything."), @@ -843,7 +843,7 @@ protocol Chat { text.contains("- `struct Response` — An HTTP response, by its status code."), "{text}" ); - let lone = hover_in("chat.ids", "use types\n", "types", 0).unwrap(); + let lone = hover_in("chat.ids", "use package::types\n", "types", 0).unwrap(); assert!( lone.contains("module types"), "a lone word on a `use` line: {lone}" @@ -852,7 +852,7 @@ protocol Chat { #[test] fn a_directory_over_a_schema_lists_both() { - let text = hover_in("chat.ids", "use api::common::Error\n", "api", 0).unwrap(); + let text = hover_in("chat.ids", "use package::api::common::Error\n", "api", 0).unwrap(); assert!(text.contains("module api\n"), "{text}"); assert!(text.contains("The API."), "{text}"); assert!( diff --git a/src/handlers/references.rs b/src/handlers/references.rs index ad5a752..71572fc 100644 --- a/src/handlers/references.rs +++ b/src/handlers/references.rs @@ -161,7 +161,7 @@ struct User { #[test] fn test_find_references_across_files_from_a_usage() { - let chat_source = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let chat_source = "use package::types::Message\n\nstruct S {\n m: Message\n}\n"; let types_source = "struct Message {\n text: string\n}\n"; let chat_uri = Url::parse("file:///chat.ids").unwrap(); let types_uri = Url::parse("file:///types.ids").unwrap(); diff --git a/src/handlers/rename.rs b/src/handlers/rename.rs index b44cd5a..b72c005 100644 --- a/src/handlers/rename.rs +++ b/src/handlers/rename.rs @@ -221,9 +221,9 @@ struct Request { #[test] fn test_rename_across_files_updates_use_lines_and_keeps_aliases() { let types_source = "struct Message {\n text: string\n}\n"; - let chat_source = "use types::Message\n\nstruct S {\n m: Message\n}\n"; - let aliased_source = "use types::Message as Msg\n\nstruct T {\n m: Msg\n}\n"; - let other_source = "use other::Message\n\nstruct U {\n m: Message\n}\n"; + let chat_source = "use package::types::Message\n\nstruct S {\n m: Message\n}\n"; + let aliased_source = "use package::types::Message as Msg\n\nstruct T {\n m: Msg\n}\n"; + let other_source = "use package::other::Message\n\nstruct U {\n m: Message\n}\n"; let other_decl = "struct Message {\n unrelated: bool\n}\n"; let types_uri = Url::parse("file:///types.ids").unwrap(); @@ -257,8 +257,8 @@ struct Request { assert_eq!( edits_by_file(edit), vec![ - ("aliased.ids".into(), 0, 11), - ("chat.ids".into(), 0, 11), + ("aliased.ids".into(), 0, 20), + ("chat.ids".into(), 0, 20), ("chat.ids".into(), 3, 7), ("types.ids".into(), 0, 7), ], @@ -269,7 +269,7 @@ struct Request { #[test] fn test_rename_started_on_an_alias_is_refused() { let types_source = "struct Message {\n text: string\n}\n"; - let aliased_source = "use types::Message as Msg\n\nstruct T {\n m: Msg\n}\n"; + let aliased_source = "use package::types::Message as Msg\n\nstruct T {\n m: Msg\n}\n"; let aliased_uri = Url::parse("file:///aliased.ids").unwrap(); let edit = rename_symbol_with_project( @@ -289,7 +289,7 @@ struct Request { fn test_prepare_rename_returns_the_word_range_or_nothing() { let types_source = "struct Message {\n text: string\n}\n"; let aliased_source = - "use types::Message as Msg\n\nstruct T {\n m: Msg\n s: string\n}\n"; + "use package::types::Message as Msg\n\nstruct T {\n m: Msg\n s: string\n}\n"; let aliased_uri = Url::parse("file:///aliased.ids").unwrap(); let project = [( Url::parse("file:///types.ids").unwrap(), @@ -299,11 +299,11 @@ struct Request { let range = prepare_rename_with_project( aliased_source, &aliased_uri, - Position::new(0, 14), + Position::new(0, 23), &project, ) .expect("`Message` in the `use` line is renameable"); - assert_eq!((range.start.character, range.end.character), (11, 18)); + assert_eq!((range.start.character, range.end.character), (20, 27)); assert!(prepare_rename_with_project( aliased_source, From fd5e629c3082e199cc4db56fcce69ad8185ed0d8 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 15 Nov 2026 08:00:58 +0800 Subject: [PATCH 2/3] Fix test expectations: use-line columns shift, prose restored, bounded fixture --- src/analysis/diagnostics.rs | 4 ++-- src/analysis/project.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/analysis/diagnostics.rs b/src/analysis/diagnostics.rs index d31f132..947daad 100644 --- a/src/analysis/diagnostics.rs +++ b/src/analysis/diagnostics.rs @@ -1665,7 +1665,7 @@ struct User { assert_eq!( dataless(&bad), ["an array of `Empty` carries only its length: `Empty` has no data, so each element \ - would take no bytes — Struct 'Batch', field 'items' — give `Empty` a field, or use package::a \ + would take no bytes — Struct 'Batch', field 'items' — give `Empty` a field, or use a \ count (`u32`) instead"] ); assert_eq!((bad[0].2, bad[0].3), (3, 4), "at the field"); @@ -2805,7 +2805,7 @@ mod bare_own_path_tests { #[test] fn a_bare_path_to_an_own_schema_is_core_s_error_worded_as_core_words_it() { - let chat = "use types::Message\n\nstruct S {\n m: Message\n}\n"; + let chat = "use types::Message\n\nstruct S {\n id: u64\n}\n"; let found = diagnostics_of(&package(chat)); assert_eq!(found.len(), 1, "{found:#?}"); let d = &found[0]; diff --git a/src/analysis/project.rs b/src/analysis/project.rs index 2138666..8988cff 100644 --- a/src/analysis/project.rs +++ b/src/analysis/project.rs @@ -810,7 +810,7 @@ mod tests { assert_eq!( lines(&refs), vec![ - ("chat.ids".into(), 0, 11), + ("chat.ids".into(), 0, 20), ("chat.ids".into(), 3, 18), ("chat.ids".into(), 3, 30) ], @@ -885,7 +885,7 @@ mod tests { let refs = project.references(&target); assert_eq!( lines(&refs), - vec![("chat.ids".into(), 0, 11)], + vec![("chat.ids".into(), 0, 20)], "`m: Message` is the local struct; only the `use` line names `types`'s" ); } From 32352b28539c288173baa13dce89d90f3f6b62f4 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Sun, 15 Nov 2026 08:19:48 +0800 Subject: [PATCH 3/3] Pin the generators at their entry-point revisions (comline-rust dd1c29e, comline-typescript d377fbf) --- Cargo.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 466226f..1a27b75 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,8 +44,8 @@ comline-core = { git = "https://github.com/ComlineProject/core", rev = "14ce5465 # generators' `SUPPORT` tables are read; nothing is generated. Pinned to the # same commits as the CLI, so a build has one `comline-codegen`. comline-codegen = { git = "https://github.com/ComlineProject/generation", rev = "e22109e1a6ca3c8e5a63338e2fe9acda44123ee1" } -comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "2d2c8853727929a7b350b3017c9ff86cb2ec8911" } -comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "c44b39d68035bd968cec0cd75afb6c6230c4ab76" } +comline-codegen-rust = { git = "https://github.com/ComlineProject/comline-rust", rev = "dd1c29e6560a0ffd7893c59715b31d43b88c585f" } +comline-codegen-typescript = { git = "https://github.com/ComlineProject/comline-typescript", rev = "d377fbf07cf6c0f004e9d5dd4fbd6fa15ea9d0bc" } # `server`-only. tower-lsp = { version = "0.20.0", optional = true }