From 1e902553065ac98fb0a8058718fe4f27ee7af036 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:31:42 +0800 Subject: [PATCH 1/8] Pin the specification at 0b376dd (specification#17, the references cases) Vendors its cases: the new references group, and the imports cases that now also expect reference::not-in-scope or no second error. core's runner fails them until the rule is built. Refs #281, #290. --- core/Cargo.toml | 2 +- core/tests/spec/REV | 2 +- core/tests/spec/cases/imports.json | 16 +- core/tests/spec/cases/references.json | 1179 +++++++++++++++++++++++++ 4 files changed, 1191 insertions(+), 8 deletions(-) create mode 100644 core/tests/spec/cases/references.json diff --git a/core/Cargo.toml b/core/Cargo.toml index 18e30ba..0dc4373 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -27,7 +27,7 @@ comline-ir-formats = { path = "formats" } # The specification's catalog of shared names: guarantees, facts and their # values, the official encodings' aliases and frozen spellings. no_std and # dependency-free, so the IR-only build has it too. -comline-catalog = { git = "https://github.com/ComlineProject/specification", rev = "16dfe40d835b85b45de07131181339fe3e9f0ccb" } +comline-catalog = { git = "https://github.com/ComlineProject/specification", rev = "0b376dd6b6e3c1ee64b46c88b29b988b47d01d39" } # General eyre = "0.6.8" diff --git a/core/tests/spec/REV b/core/tests/spec/REV index f96f2ef..816a162 100644 --- a/core/tests/spec/REV +++ b/core/tests/spec/REV @@ -1 +1 @@ -16dfe40d835b85b45de07131181339fe3e9f0ccb +0b376dd6b6e3c1ee64b46c88b29b988b47d01d39 diff --git a/core/tests/spec/cases/imports.json b/core/tests/spec/cases/imports.json index 952f8d7..11e918f 100644 --- a/core/tests/spec/cases/imports.json +++ b/core/tests/spec/cases/imports.json @@ -35,7 +35,7 @@ }, { "id": "imports/bare-own-namespace", - "description": "a bare path to the package's own schema as a whole is an error", + "description": "a bare path to the package's own schema as a whole is an error, and so is the bare Blob after it, as a whole-namespace use brings in only its name: every error is reported", "packages": [ { "name": "app", @@ -60,6 +60,10 @@ { "code": "import::bare-own-schema-path", "severity": "error" + }, + { + "code": "reference::not-in-scope", + "severity": "error" } ] } @@ -409,7 +413,7 @@ }, { "id": "imports/unknown-first-segment", - "description": "a bare path that is neither a dependency, std nor one of the package's schemas is unresolved, not this error", + "description": "a bare path that is neither a dependency, std nor one of the package's schemas is unresolved, not this error; the use still brings Blob into scope, so the bare Blob after it is no second error, as in Rust", "packages": [ { "name": "app", @@ -499,7 +503,7 @@ "schemas": [ { "path": "src/api.ids", - "text": "struct Upload {\n blob: Blob\n}\n" + "text": "struct Upload {\n size: u32\n}\n" } ], "dependencies": [ @@ -539,7 +543,7 @@ "schemas": [ { "path": "src/api.ids", - "text": "struct Upload {\n blob: Blob\n}\n" + "text": "struct Upload {\n size: u32\n}\n" } ], "dependencies": [ @@ -579,7 +583,7 @@ "schemas": [ { "path": "src/api.ids", - "text": "struct Upload {\n blob: Blob\n}\n" + "text": "struct Upload {\n size: u32\n}\n" } ], "dependencies": [ @@ -619,7 +623,7 @@ "schemas": [ { "path": "src/api.ids", - "text": "struct Upload {\n blob: Blob\n}\n" + "text": "struct Upload {\n size: u32\n}\n" } ], "dependencies": [ diff --git a/core/tests/spec/cases/references.json b/core/tests/spec/cases/references.json new file mode 100644 index 0000000..8f7675e --- /dev/null +++ b/core/tests/spec/cases/references.json @@ -0,0 +1,1179 @@ +{ + "$schema": "../../specs/gen/compiler.schema.json", + "group": "references", + "cases": [ + { + "id": "references/namespace-qualified", + "description": "after use package::types, types::User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/namespace-bare-refused", + "description": "after use package::types a bare User is not in scope: the use brings in only types (fix, offered because User is declared in types: add use package::types::User, or write types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/namespace-alias-qualified", + "description": "after use package::types as t, t::User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types as t\n\nstruct Account {\n owner: t::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/namespace-alias-original-refused", + "description": "after use package::types as t only the alias t is in scope, not types, which the alias replaces (fix: write t::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types as t\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/item-bare", + "description": "after use package::types::User, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::User\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/item-qualified-refused", + "description": "after use package::types::User, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::User\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/braces-bare", + "description": "after use package::types::{User, Order}, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::{User, Order}\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/braces-qualified-refused", + "description": "after use package::types::{User, Order}, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::{User, Order}\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/glob-bare", + "description": "after use package::types::*, User reaches the item", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::*\n\nstruct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/glob-qualified-refused", + "description": "after use package::types::*, types is not in scope (fix: write User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types::*\n\nstruct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/no-use-bare-refused", + "description": "a bare User with no use is not in scope (fix, offered because User is declared in package::types: add use package::types::User, or write package::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/no-use-qualified-refused", + "description": "types::User with no use is not rooted in a name in scope (fix, offered because the package declares types::User: add use package::types, or write package::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/nowhere-bare-refused", + "description": "a bare Nowhere that no schema of the package or its dependencies declares is not in scope (no fix that adds a use is offered: nothing declares it)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::types\n\nstruct Account {\n owner: Nowhere\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/nowhere-qualified-refused", + "description": "nope::types::User, whose first segment matches no name in scope, root or schema, is not in scope (no fix that adds a use is offered: nothing is named nope)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: nope::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/defined-twice-local-and-use", + "description": "use package::billing::Invoice and struct Invoice in the same schema define Invoice twice (fix: rename one, or import with an alias: use package::billing::Invoice as BillingInvoice)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice\n\nstruct Invoice {\n data: char[max 64]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::defined-twice", + "severity": "error" + } + ] + } + }, + { + "id": "references/defined-twice-two-uses", + "description": "use package::a::User and use package::b::User bring in User twice (fix: rename one, or import with an alias: use package::b::User as BUser)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/a.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/b.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::a::User\nuse package::b::User\n\nstruct Account {\n id: u32\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::defined-twice", + "severity": "error" + } + ] + } + }, + { + "id": "references/alias-resolves-local-clash", + "description": "use package::billing::api::Invoice as BillingInvoice beside a local Invoice defines each name once", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice as BillingInvoice\n\nstruct Invoice {\n data: char[max 64]\n}\n\nstruct Account {\n billed: BillingInvoice\n own: Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/alias-resolves-two-uses", + "description": "use package::a::User beside use package::b::User as BUser defines each name once", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/a.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/b.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::a::User\nuse package::b::User as BUser\n\nstruct Account {\n first: User\n second: BUser\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-package", + "description": "package::types::User in a field needs no use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: package::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-package-nested", + "description": "package:: reaches a schema in a directory from one beside it, in a field", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "struct Account {\n owner: package::shapes::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-parent", + "description": "parent::common::Error in a field reaches a schema one level up from the importing schema's namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/common.ids", + "text": "struct Error {\n code: u32\n}\n" + }, + { + "path": "src/shapes/api.ids", + "text": "struct Account {\n owner: parent::common::Error\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-self", + "description": "self::nested::Type in a field reaches a schema under the importing schema's own namespace", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: self::nested::Type\n}\n" + }, + { + "path": "src/api/nested.ids", + "text": "struct Type {\n id: u32\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-std", + "description": "std::http::Request in a field needs no use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: std::http::Request\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-dependency", + "description": "a dependency's greeting::hello::Greeting in a field needs no use", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "struct Account {\n owner: greeting::hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/full-own-schema-unrooted-refused", + "description": "a full path to the package's own schema that doesn't start at package, parent or self is not rooted (fix, offered because the schema exists: write package::shapes::types::User)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/shapes/types.ids", + "text": "struct User {\n id: u32\n}\n\nstruct Order {\n id: u32\n}\n" + }, + { + "path": "src/api.ids", + "text": "struct Account {\n owner: shapes::types::User\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/descend-namespace", + "description": "after use package::billing, billing::api::Invoice reaches the nested schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nstruct Account {\n owner: billing::api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-alias", + "description": "after use package::billing as b, b::api::Invoice reaches the nested schema", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing as b\n\nstruct Account {\n owner: b::api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-dependency", + "description": "after use greeting::hello, hello::Greeting reaches the dependency's item", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use greeting::hello\n\nstruct Account {\n owner: hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-dependency-name", + "description": "after use greeting, a dependency's name on its own, greeting::hello::Greeting reaches the dependency's item", + "packages": [ + { + "name": "greeting", + "config": "congregation greeting\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/hello.ids", + "text": "struct Greeting {\n text: char[max 64]\n}\n" + } + ], + "dependencies": [] + }, + { + "name": "app", + "config": "congregation app\nspecification_version = 1\ndependencies = {\n greeting = {\n path = \"../greeting\"\n }\n}\n", + "schemas": [ + { + "path": "src/api.ids", + "text": "use greeting\n\nstruct Account {\n owner: greeting::hello::Greeting\n}\n" + } + ], + "dependencies": [ + { + "name": "greeting" + } + ] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/descend-skips-a-segment-refused", + "description": "after use package::billing, api is not in scope (fix, offered because billing::api exists: write billing::api::Invoice, or add use package::billing::api)", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nstruct Account {\n owner: api::Invoice\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "reference::qualifier-not-in-scope", + "severity": "error" + } + ] + } + }, + { + "id": "references/resolved-item", + "description": "use package::billing::api::Invoice, then Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api::Invoice\n\nprotocol Orders {\n function send(i: Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/resolved-namespace", + "description": "use package::billing::api, then api::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api\n\nprotocol Orders {\n function send(i: api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/resolved-descent", + "description": "use package::billing, then billing::api::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing\n\nprotocol Orders {\n function send(i: billing::api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/resolved-alias", + "description": "use package::billing::api as b, then b::Invoice, reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::billing::api as b\n\nprotocol Orders {\n function send(i: b::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/resolved-full-path", + "description": "package::billing::api::Invoice with no use reaches billing::api::Invoice", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "protocol Orders {\n function send(i: package::billing::api::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Orders", + "given_up": [] + } + ], + "builds": true, + "diagnostics": [] + } + }, + { + "id": "references/resolved-decoy", + "description": "use package::archive, then archive::Invoice, reaches the unbounded Invoice, which an unmarked protocol can't use: the other cases reached billing's", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/archive.ids", + "text": "struct Invoice {\n data: string\n}\n" + }, + { + "path": "src/billing/api.ids", + "text": "struct Invoice {\n data: char[max 64]\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::archive\n\nprotocol Orders {\n function send(i: archive::Invoice);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "references/existing-package-unchanged", + "description": "use package::models and models::Blob, as written before the rule, freezes the same protocols as the item use does in bounded/other-schema-marked", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n\n@unverified = \"the uploader streams whatever it's given\"\nprotocol Upload {\n function put(b: Blob);\n}\n" + }, + { + "path": "src/api.ids", + "text": "use package::models\n\n@unverified = \"orders carry the upload\"\nprotocol Orders {\n function send(b: models::Blob);\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [ + { + "name": "Upload", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the uploader streams whatever it's given" + } + ] + }, + { + "name": "Orders", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "orders carry the upload" + } + ] + } + ], + "builds": true, + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] + } + } + ] +} From bd1c99b409426ce2008b216f29bf85cdfedf5de6 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:31:42 +0800 Subject: [PATCH 2/8] references: qualified references follow the Rust model (#290, #286) A name in scope is a declaration of the schema, what a use brings in (its alias, else its last segment) or a root: package, parent, self, std or a dependency's name. A whole-namespace use brings in only its name. A qualified reference resolves its first segment that way and walks down; a full path from a root needs no use. It is frozen as its resolved path, so api::Invoice, billing::api::Invoice and an alias's b::Invoice are all billing::api::Invoice, and the frozen IR of an existing package is as it was. reference::not-in-scope, reference::qualifier-not-in-scope and reference::defined-twice carry their fixes, and every error is reported. An unresolved use still brings its name in. A dependency's name used on its own, and a directory of schemas, are accepted as uses. The import did-you-mean suggests package::types::User for one of the package's own schemas (#286). Refs #281. --- .../package/config/ir/compiler/interpret.rs | 48 +- core/src/package/stdlib.rs | 22 +- .../schema/ir/compiler/alias_resolution.rs | 7 + .../src/schema/ir/compiler/import_resolver.rs | 117 ++- .../ir/compiler/interpreter/incremental.rs | 27 +- core/src/schema/ir/compiler/mod.rs | 1 + core/src/schema/ir/compiler/references.rs | 986 ++++++++++++++++++ core/src/schema/ir/frozen/types.rs | 14 + core/src/schema/ir/frozen/unit.rs | 74 ++ core/src/schema/ir/resolve.rs | 130 ++- core/src/schema/ir/validation/validator.rs | 27 + core/tests/schema/ir/imports.rs | 70 +- core/tests/schema/ir/mod.rs | 1 + core/tests/schema/ir/references.rs | 496 +++++++++ core/tests/schema/ir/type_resolution.rs | 25 +- 15 files changed, 1982 insertions(+), 63 deletions(-) create mode 100644 core/src/schema/ir/compiler/references.rs create mode 100644 core/tests/schema/ir/references.rs diff --git a/core/src/package/config/ir/compiler/interpret.rs b/core/src/package/config/ir/compiler/interpret.rs index 4178dc7..1c3c39f 100644 --- a/core/src/package/config/ir/compiler/interpret.rs +++ b/core/src/package/config/ir/compiler/interpret.rs @@ -11,6 +11,7 @@ use crate::schema::ir::compiler::import_resolver::{ check_imports, resolve_use_to_schema, use_brings_into_scope, ImportResolver, ProjectImports, }; use crate::schema::ir::compiler::interpreter::IncrementalInterpreter; +use crate::schema::ir::compiler::references::{check_references, Scope}; use crate::schema::ir::compiler::settings::enforcement::check_settings_enforcement; use crate::schema::ir::compiler::settings::resolution::check_settings_conflicts; use crate::schema::ir::compiler::settings::severity::resolve_diagnostic_overrides; @@ -90,6 +91,11 @@ pub fn interpret_context(project_context: &ProjectContext) -> Result<()> { let declarations = { schema_context.borrow().declarations.clone() }; let namespace = { schema_context.borrow().namespace.clone() }; + // Every error of what the schema names is reported, not the first: + // the imports that don't resolve, and the names written that nothing + // brought into scope. A `use` that doesn't resolve still brings its + // name in, so the one never causes the other. + let mut unnamed = false; if let Err(errors) = check_imports(&declarations, &namespace, project_context) { let rendered: Vec = errors .iter() @@ -100,6 +106,21 @@ pub fn interpret_context(project_context: &ProjectContext) -> Result<()> { namespace.join("::"), rendered.join("\n\n") )); + unnamed = true; + } + if let Err(errors) = check_references(&declarations, &namespace, project_context) { + let rendered: Vec = errors + .iter() + .map(|error| schema_context.borrow().render(error)) + .collect(); + schema_errors.push(format!( + "Schema '{}' has names that aren't in scope:\n{}", + namespace.join("::"), + rendered.join("\n\n") + )); + unnamed = true; + } + if unnamed { continue; } @@ -468,7 +489,9 @@ fn imports_foreign( }); }; - // A qualified name may name its schema outright. + // A qualified name is a path from the package's root (core#290): it names + // its schema outright, and no `use` of the schema is asked about it. + let mut named_outright = false; if let Some(qualifier) = qualifier { let parts: Vec = qualifier.split("::").map(str::to_string).collect(); if let Some((schema, remaining)) = @@ -476,10 +499,11 @@ fn imports_foreign( { if remaining.is_empty() { declares(&schema, bare); + named_outright = true; } } } - for decl in declarations { + for decl in declarations.iter().filter(|_| !named_outright) { let Declaration::Use(use_stmt) = &decl.value else { continue; }; @@ -594,6 +618,26 @@ fn schema_imports(project_context: &ProjectContext) -> HashMap Vec> { return vec![]; }; let resolver = ImportResolver::new(vec![], HashMap::new(), None); - document + let mut targets: Vec> = document .0 .iter() .filter_map(|decl| match &decl.value { @@ -74,7 +75,16 @@ fn std_imports(namespace: &[String], source: &str) -> Vec> { }) .map(|resolved| resolved.absolute_namespace) .filter(|target| target.first().map(String::as_str) == Some(NAMESPACE)) - .collect() + .collect(); + // A full path in a type position needs no `use`: `std::http::Request` + // (core#290). + targets.extend( + named_types(&document.0) + .into_iter() + .filter(|written| written.name.starts_with("std::")) + .map(|written| written.name.split("::").map(String::from).collect::>()), + ); + targets } /// The schema a `use` of `target` resolves to, the way the build matches it: @@ -112,6 +122,14 @@ mod tests { ); } + #[test] + fn a_std_path_in_a_type_merges_its_schema_with_no_use() { + let sources = [schema(&["api"], "struct Call {\n request: std::http::Request\n}\n")]; + assert_eq!(namespaces(&sources), ["std::http"]); + // A name that only looks like one isn't. + assert!(namespaces(&[schema(&["api"], "struct Call {\n request: stdlib::http::Request\n}\n")]).is_empty()); + } + #[test] fn an_unknown_std_path_merges_nothing() { // `check_imports` then reports it, with a suggestion from std. diff --git a/core/src/schema/ir/compiler/alias_resolution.rs b/core/src/schema/ir/compiler/alias_resolution.rs index be7cd6d..2f92e2f 100644 --- a/core/src/schema/ir/compiler/alias_resolution.rs +++ b/core/src/schema/ir/compiler/alias_resolution.rs @@ -30,6 +30,7 @@ use std::collections::{HashMap, HashSet}; use crate::package::config::ir::context::ProjectContext; use crate::schema::idl::grammar::{Declaration, Type}; use crate::schema::ir::compiler::import_resolver::{find_schema_bringing_into_scope, schema_declares_symbol}; +use crate::schema::ir::compiler::references::Scope; use crate::schema::ir::validation::validator::is_primitive; use crate::diagnostics::{Diagnostic, DiagnosticCode}; @@ -246,6 +247,12 @@ fn first_unresolvable_name( if is_primitive(&bare) { return None; } + // A qualified name is read by the rule for them (core#290): a + // path from a name in scope, or from a root. + if let (true, Some((current_namespace, project_context))) = (full.contains("::"), use_context) { + let scope = Scope::new(declarations, current_namespace, project_context); + return (!scope.exists(&full)).then_some(full); + } if alias_map.contains_key(&bare) { return None; } diff --git a/core/src/schema/ir/compiler/import_resolver.rs b/core/src/schema/ir/compiler/import_resolver.rs index 22e4ed4..cf8b119 100644 --- a/core/src/schema/ir/compiler/import_resolver.rs +++ b/core/src/schema/ir/compiler/import_resolver.rs @@ -594,12 +594,30 @@ pub struct ProjectImports<'a> { } impl ProjectImports<'_> { + /// The schema that declares what `name` names, and its name there. A + /// qualified type is frozen as its path from the package's root (core#290), + /// so it is the schema by that namespace; one that isn't (a validator + /// called `validators::StringBounds`, as written) and a bare name are read + /// through the schema's `use`s. fn declaring_schema(&self, name: &str) -> Option<(Rc>, String)> { let bare = name.rsplit("::").next()?.to_string(); + if let Some(schema) = self.by_path(name) { + return Some((schema, bare)); + } let schema = find_schema_bringing_into_scope(&bare, self.declarations, self.namespace, self.project)?; Some((schema, bare)) } + + /// The schema whose namespace is the qualifier of `name`, when it + /// declares the name. + fn by_path(&self, name: &str) -> Option>> { + let (qualifier, bare) = name.rsplit_once("::")?; + let parts: Vec = qualifier.split("::").map(str::to_string).collect(); + let (schema, remaining) = self.project.find_schema_by_import_namespace_parts(&parts)?; + let declared = remaining.is_empty() && importable_names(&schema.borrow()).iter().any(|n| n == bare); + declared.then_some(schema) + } } impl ImportLookup for ProjectImports<'_> { @@ -609,6 +627,10 @@ impl ImportLookup for ProjectImports<'_> { fn encodings(&self) -> crate::schema::ir::unverified::Encodings<'_> { crate::schema::ir::unverified::Encodings::of(self.project) } + fn reaches(&self, name: &str) -> bool { + self.by_path(name).is_some() + } + fn validator_targets(&self, name: &str) -> Option> { let (schema, bare) = self.declaring_schema(name)?; let schema = schema.borrow(); @@ -796,7 +818,12 @@ pub fn declared_symbol_names(schema_context: &SchemaContext) -> Vec { /// Whether a `use` resolving to `resolved` (with `remaining` path segments /// left over after the longest-prefix schema match, and an optional `as` -/// `alias`) brings the bare name `name` into scope. The branch order is +/// `alias`) brings the bare name `name` into scope. This is the older, wider +/// reading, where a whole-namespace `use` brings in every name the schema has: +/// the names a schema's `use`s are still read for (validators, constants, the +/// errors a function throws). A type's name is read by +/// [`references::Scope`](super::references::Scope), where it brings in its own +/// name only (core#290). The branch order is /// load-bearing - glob, then explicit multi-import symbols, then a /// whole-namespace `use`, then the remaining path/alias - and is the only /// correct statement of this rule; shared by [`find_schema_bringing_into_scope`] @@ -907,6 +934,26 @@ pub fn absolute_first_segment(use_path: &UsePath) -> Option<&str> { (!matches!(first, "self" | "parent" | "package")).then_some(first) } +/// Whether `parts` is a namespace that has no schema of its own: a +/// dependency's name or `std` on its own, or a directory of the project's +/// schemas (`billing`, with `billing::api` a schema). +pub(crate) fn is_namespace( + project_context: &ProjectContext, + dependencies: &HashSet, + parts: &[String], +) -> bool { + if let [only] = parts { + if only == stdlib::NAMESPACE || dependencies.contains(only) { + return true; + } + } + !parts.is_empty() + && project_context.schema_contexts.iter().any(|schema| { + let schema = schema.borrow(); + schema.namespace.len() > parts.len() && schema.namespace.starts_with(parts) + }) +} + /// A `use` path as it is written, without its alias. fn written_path(use_path: &UsePath) -> String { match use_path { @@ -951,22 +998,31 @@ fn bare_own_schema_path( .with_help(format!( "write `{write}`: a package's own schemas are reached as `package::...`, `parent::...` or `self::...`" )); - match own_path_fix(source, span, first, &write) { + match own_path_fix(source, span, first, &format!("Write `{write}`"), "package::", 0) { Some(fix) => diagnostic.with_fix(fix), None => diagnostic, } } -/// Inserting `package::` where the `use` declaration at `span` names `first`, -/// the first segment of its path; `None` when `source` isn't there, or the -/// declaration isn't `use`, whitespace, and then `first`. -fn own_path_fix(source: Option<&str>, span: (usize, usize), first: &str, write: &str) -> Option { +/// Replacing the `replaced` bytes where the `use` declaration at `span` names +/// `first`, the first segment of its path, with `text` (inserting, for 0, as +/// `package::` is put in front of a bare path); `None` when `source` isn't +/// there, or the declaration isn't `use`, whitespace, and then `first`. +fn own_path_fix( + source: Option<&str>, + span: (usize, usize), + first: &str, + title: &str, + text: &str, + replaced: usize, +) -> Option { let source = source?; let after_use = source.get(span.0..span.1)?.strip_prefix("use")?; let at = span.1 - after_use.trim_start().len(); - source.get(at..)?.starts_with(first).then(|| { - Fix::replace(format!("Write `{write}`"), (at, at), "package::") - }) + source + .get(at..)? + .starts_with(first) + .then(|| Fix::replace(title, (at, at + replaced), text)) } /// Every `use` in `declarations` that doesn't resolve, as validation @@ -1061,6 +1117,21 @@ pub fn check_imports( continue; } + // A namespace with no schema of its own brings its name into + // scope, to qualify with (core#290): a dependency's name or `std` + // on its own, or a directory of schemas (`use package::billing`). + // A directory reached by a bare path is the same error as a schema. + if target.resolved.symbols.is_empty() + && is_namespace(project_context, &dependencies, &target.resolved.absolute_namespace) + { + if let Some(written) = absolute_first_segment(&use_stmt.path) { + if written != stdlib::NAMESPACE && !dependencies.contains(written) { + errors.push(bare_own_schema_path(&use_stmt.path, written, decl.span, source.as_deref())); + } + } + continue; + } + if first == stdlib::NAMESPACE { errors.push(unresolved(unknown_std_path(&target.resolved.absolute_namespace))); continue; @@ -1070,13 +1141,37 @@ pub fn check_imports( "no schema in this package or its dependencies matches '{}'", target.resolved.absolute_namespace.join("::") ); + let mut fix = None; if !top_level.contains(first) && !dependencies.contains(first) { let known = top_level.iter().chain(&dependencies).map(String::as_str); if let Some(suggestion) = closest(first, known) { - context.push_str(&format!(" - did you mean '{suggestion}'?")); + // One of the package's own schemas is reached through + // `package::`, so that is what is suggested (core#286); a + // dependency's name and `std` are absolute as they are. + let own = top_level.contains(&suggestion) + && !dependencies.contains(&suggestion) + && suggestion != stdlib::NAMESPACE + && absolute_first_segment(&use_stmt.path) == Some(first); + if own { + let written = written_path(&use_stmt.path); + let corrected = format!("package::{suggestion}{}", &written[first.len()..]); + context.push_str(&format!(" - did you mean '{corrected}'?")); + fix = own_path_fix( + source.as_deref(), + decl.span, + first, + &format!("Write `{corrected}`"), + &format!("package::{suggestion}"), + first.len(), + ); + } else { + context.push_str(&format!(" - did you mean '{suggestion}'?")); + } } } - errors.push(unresolved(context)); + let mut diagnostic = unresolved(context); + diagnostic.fix = fix; + errors.push(diagnostic); continue; }; diff --git a/core/src/schema/ir/compiler/interpreter/incremental.rs b/core/src/schema/ir/compiler/interpreter/incremental.rs index 11d8aa9..be69bd2 100644 --- a/core/src/schema/ir/compiler/interpreter/incremental.rs +++ b/core/src/schema/ir/compiler/interpreter/incremental.rs @@ -7,6 +7,7 @@ use crate::schema::idl::grammar::{ self, Annotation, AnnotationValue, Declaration, Expression, UsePath, }; use crate::schema::ir::compiler::alias_resolution::check_aliases; +use crate::schema::ir::compiler::references::{check_references, Scope}; use crate::schema::ir::compiler::settings::resolution::check_settings_conflicts; use crate::schema::ir::compiler::import_resolver::{size_constant, check_imports, declared_symbol_names, find_schema_bringing_into_scope, resolve_use_to_schema, @@ -49,7 +50,18 @@ impl IncrementalInterpreter { use_context: Option<(&[String], &ProjectContext)>, ) -> Result, Vec> { if let Some((current_namespace, project_context)) = use_context { - check_imports(&declarations, current_namespace, project_context)?; + // Both are reported, as `comline build` reports them. + let mut errors = check_imports(&declarations, current_namespace, project_context) + .err() + .unwrap_or_default(); + errors.extend( + check_references(&declarations, current_namespace, project_context) + .err() + .unwrap_or_default(), + ); + if !errors.is_empty() { + return Err(errors); + } } check_aliases(&declarations, use_context)?; crate::schema::ir::compiler::bounds::check_bounds(&declarations, use_context)?; @@ -363,6 +375,19 @@ impl IncrementalInterpreter { } } + // A qualified type is frozen as its path from the package's root + // (core#290): `api::Invoice` after `use package::billing::api`, an + // alias's `b::Invoice` and a full `package::billing::api::Invoice` are + // all `billing::api::Invoice`. A bare name is frozen as written. + if let Some((namespace, project)) = use_context { + let scope = Scope::new(&size_declarations, namespace, project); + for unit in &mut frozen_units { + unit.for_each_type_mut(&mut |ty| { + *ty = ty.map_named(&mut |name| scope.frozen(name).map(TypeRef::Named)); + }); + } + } + // Re-exported foreign errors named by a `throws`, in ordinal order, // after the local declarations. frozen_units.extend(reexports); diff --git a/core/src/schema/ir/compiler/mod.rs b/core/src/schema/ir/compiler/mod.rs index 3df7a8a..3737c24 100644 --- a/core/src/schema/ir/compiler/mod.rs +++ b/core/src/schema/ir/compiler/mod.rs @@ -2,6 +2,7 @@ pub mod interpreter; pub mod interpreted; pub mod import_resolver; +pub mod references; pub mod alias_resolution; pub mod annotation_forms; pub mod bounds; diff --git a/core/src/schema/ir/compiler/references.rs b/core/src/schema/ir/compiler/references.rs new file mode 100644 index 0000000..f092dfb --- /dev/null +++ b/core/src/schema/ir/compiler/references.rs @@ -0,0 +1,986 @@ +//! What a type written in a schema names: the Rust model (core#290). +//! +//! A name in scope in a schema is one of +//! +//! - a declaration of the schema itself; +//! - what a `use` of the schema brings in: its alias, else the last segment of +//! its path (an alias replaces the name, `use package::types as t` brings in +//! `t` and not `types`), or every name of a `{...}` or `*`; +//! - a root: `package`, `parent`, `self`, `std`, or a dependency's name. +//! +//! A whole-namespace `use` (`use package::types`) brings in only its own name, +//! `types`, and nothing in it: `types::User` reaches the item, a bare `User` +//! needs `use package::types::User`. A qualified reference resolves its first +//! segment by that rule, then walks down: after `use package::billing`, +//! `billing::api::Invoice` is the schema `billing::api`'s `Invoice`. A full +//! path from a root needs no `use` (`package::types::User`, +//! `parent::common::Error`, `self::nested::Type`, `std::http::Request`, a +//! dependency's `greeting::hello::Greeting`). +//! +//! A qualified reference freezes as its resolved path, from the package's root +//! (`api::Invoice`, `billing::api::Invoice` and an alias's `b::Invoice` all +//! freeze as `billing::api::Invoice`), so the frozen IR and its hashes are the +//! same however the file spells it. A bare name freezes as written. +//! +//! [`Scope`] is that rule over a schema's declarations and the project; +//! [`check_references`] reports what it refuses, every error at once: +//! +//! - [`NOT_IN_SCOPE`]: a bare name nothing brought in; +//! - [`QUALIFIER_NOT_IN_SCOPE`]: a qualified name whose first segment is +//! neither a name in scope nor a root; +//! - [`DEFINED_TWICE`]: a name a `use` brings in that the schema also declares, +//! or that two `use`s bring in. +//! +//! A `use` that fails to resolve (`import::unresolved`, reported by +//! [`check_imports`](super::import_resolver::check_imports)) still brings its +//! name into scope, so it never causes a second error here. +//! +//! The resolvers over the frozen IR (`compat`, the sizer, the validator's +//! lookups) read a name that is already resolved: see `schema::ir::resolve`. + +use std::collections::{HashMap, HashSet}; + +use crate::diagnostics::{Diagnostic, DiagnosticCode, Fix}; +use crate::package::config::dependency::DependencyConfig; +use crate::package::config::ir::context::ProjectContext; +use crate::package::stdlib; +use crate::schema::idl::grammar::{Declaration, Type, Use, UsePath}; +use crate::schema::ir::compiler::import_resolver::{ + importable_names, is_namespace, resolve_use_to_schema, ImportResolver, +}; +use crate::schema::ir::context::SchemaContext; +use crate::schema::ir::frozen::types::PrimitiveType; + +/// A bare name that no declaration of the schema and no `use` of it brought +/// in. The codes are in the specification's compiler cases (`references`). +pub const NOT_IN_SCOPE: DiagnosticCode = DiagnosticCode::error("reference::not-in-scope"); + +/// A qualified name whose first segment is not a name in scope, nor a root. +pub const QUALIFIER_NOT_IN_SCOPE: DiagnosticCode = + DiagnosticCode::error("reference::qualifier-not-in-scope"); + +/// A name defined twice in a schema: a `use`d item and a declaration of the +/// same name, or two `use`s that bring the same name in. +pub const DEFINED_TWICE: DiagnosticCode = DiagnosticCode::error("reference::defined-twice"); + +/// A type name as it is written in a schema, and where. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Written { + pub name: String, + /// The type it is in. A name inside an array or a union has no span of + /// its own: [`locate`] finds it in the source. + pub within: (usize, usize), +} + +/// Every type name written in `declarations`, in source order, as it is +/// written (`User`, `types::User`). Primitives, and a validator's `any`, are +/// not names. +pub fn named_types(declarations: &[rust_sitter::Spanned]) -> Vec { + let mut out = vec![]; + for decl in declarations { + match &decl.value { + Declaration::Const(c) => names_in(c.type_def(), c.type_def_span(), false, &mut out), + Declaration::Struct(s) => { + for field in s.fields() { + names_in( + field.value.field_type(), + field.value.field_type_span(), + false, + &mut out, + ); + } + } + Declaration::Error(e) => { + for field in e.fields() { + names_in( + field.value.field_type(), + field.value.field_type_span(), + false, + &mut out, + ); + } + } + Declaration::Protocol(p) => { + for function in p.functions() { + let function = &function.value; + if let Some(list) = function.args() { + let first = list.first(); + names_in(first.arg_type(), first.arg_type_span(), false, &mut out); + for rest in list.rest() { + let arg = rest.arg_type(); + names_in(arg.arg_type(), arg.arg_type_span(), false, &mut out); + } + } + if let Some(returns) = function.return_type() { + names_in( + returns.return_type(), + returns.return_type_span(), + false, + &mut out, + ); + } + } + } + Declaration::TypeAlias(a) => { + names_in(a.target_type(), a.target_type_span(), false, &mut out) + } + Declaration::Validator(v) => { + if let Some(targets) = &v.targets { + names_in(&targets.first.value, targets.first.span, true, &mut out); + for rest in &targets.rest { + names_in(&rest.target.value, rest.target.span, true, &mut out); + } + } + for property in v.properties() { + let ty = &property.value.property_type; + names_in(&ty.value, ty.span, false, &mut out); + } + } + _ => {} + } + } + out +} + +/// The names in `ty`, in the order they are written. `any` is a keyword in a +/// validator's `for`, where `any_is_keyword`. +fn names_in(ty: &Type, within: (usize, usize), any_is_keyword: bool, out: &mut Vec) { + match ty { + Type::Named(id) => { + let name = id.text.clone(); + if PrimitiveType::from_name(&name).is_some() || (any_is_keyword && name == "any") { + return; + } + out.push(Written { name, within }); + } + Type::Array(array) => names_in(array.elem_type(), within, any_is_keyword, out), + Type::Union(union) => { + for member in union.members() { + names_in(member, within, any_is_keyword, out); + } + } + _ => {} + } +} + +/// Where each of `written` is in `source`: the name's own span, or the span of +/// the type it is in (and `false`) where it can't be found. +pub fn locate(source: Option<&str>, written: &[Written]) -> Vec<((usize, usize), bool)> { + let mut cursors: HashMap<(usize, usize), usize> = HashMap::new(); + written + .iter() + .map(|w| { + let from = *cursors.get(&w.within).unwrap_or(&w.within.0); + match source.and_then(|source| find_name(source, w.within, &w.name, from)) { + Some(span) => { + cursors.insert(w.within, span.1); + (span, true) + } + None => (w.within, false), + } + }) + .collect() +} + +/// `name` as a whole name in `source[within]`, from `from` on. +fn find_name( + source: &str, + within: (usize, usize), + name: &str, + from: usize, +) -> Option<(usize, usize)> { + let text = source.get(within.0..within.1)?; + let skip = from.saturating_sub(within.0); + let part_of_name = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == ':'; + text.match_indices(name).find_map(|(at, _)| { + let before = text[..at].chars().next_back(); + let after = text[at + name.len()..].chars().next(); + let whole = !before.is_some_and(part_of_name) && !after.is_some_and(part_of_name); + (at >= skip && whole).then_some((within.0 + at, within.0 + at + name.len())) + }) +} + +/// What a `use` brought into scope a name for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Kind { + /// A declaration of a schema: a type. + Item, + /// A schema, a directory of schemas, `std` or a dependency: something to + /// qualify with. + Namespace, + /// A path that didn't resolve. It stands for whatever it needs to, so the + /// error it already is is the only one. + Unknown, +} + +/// A name a `use` brought into scope. +#[derive(Debug, Clone)] +struct Binding { + name: String, + kind: Kind, + /// What it is: the path from the package's root (or a root's), the name + /// of the item last. + path: Vec, + /// From a `*`: a declaration, or any other `use`, takes precedence. + weak: bool, + /// The `use` declaration. + span: (usize, usize), + /// A `use path` or `use path as alias`, which `as` can rename. + single: bool, + /// Written with an `as`. + aliased: bool, +} + +/// What a written name resolved to. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Resolved { + /// What the name freezes as: a bare name as written, a qualified one as + /// its path from the package's root. + pub frozen: String, + /// The schema (its namespace) and the declaration it names, when the + /// project holds them. + pub target: Option<(Vec, String)>, +} + +/// Why a written name resolved to nothing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Refusal { + /// A bare name nothing brought in. `namespace` where a `use` did bring + /// the name in, but as a namespace, which is no type. + NotInScope { namespace: bool }, + /// A qualified name whose first segment is not in scope. + QualifierNotInScope, +} + +/// The names in scope in one schema. +pub struct Scope<'p> { + namespace: Vec, + project: &'p ProjectContext, + /// `std` and the dependencies' names. + roots: HashSet, + /// What the schema declares, with where. + locals: Vec<(String, (usize, usize))>, + bindings: Vec, + /// A `*` of a path that didn't resolve: it may bring in any name. + opaque_glob: bool, + /// Where the `use`s are, and where the first declaration starts, for the + /// fix that adds one. + uses: Vec<(usize, usize)>, + first_declaration: Option, +} + +impl<'p> Scope<'p> { + /// The scope of the schema `namespace` with these `declarations`. + pub fn new( + declarations: &[rust_sitter::Spanned], + namespace: &[String], + project: &'p ProjectContext, + ) -> Self { + let mut roots: HashSet = + DependencyConfig::parse_dependencies(&project.config.assignments) + .map(|deps| deps.into_keys().collect()) + .unwrap_or_default(); + roots.insert(stdlib::NAMESPACE.to_string()); + let mut scope = Scope { + namespace: namespace.to_vec(), + project, + roots, + locals: vec![], + bindings: vec![], + opaque_glob: false, + uses: vec![], + first_declaration: None, + }; + let resolver = ImportResolver::new(vec![], Default::default(), None); + for decl in declarations { + let declared = match &decl.value { + Declaration::Use(stmt) => { + scope.uses.push(decl.span); + scope.add_use(&resolver, stmt, decl.span); + continue; + } + // The legacy `import path`: its last segment, as it always was. + Declaration::Import(import) => { + scope.add_legacy_import(&import.path(), decl.span); + continue; + } + Declaration::Const(c) => c.name(), + Declaration::Struct(s) => s.name(), + Declaration::Enum(e) => e.name(), + Declaration::Protocol(p) => p.name(), + Declaration::Error(e) => e.name(), + Declaration::Validator(v) => v.name(), + Declaration::TypeAlias(a) => a.name(), + Declaration::Settings(_) => continue, + }; + scope.first_declaration.get_or_insert(decl.span.0); + scope.locals.push((declared, decl.span)); + } + scope + } + + fn bind(&mut self, binding: Binding) { + self.bindings.push(binding); + } + + fn add_legacy_import(&mut self, path: &str, span: (usize, usize)) { + let path: Vec = path.split("::").map(str::to_string).collect(); + if let Some(name) = path.last().cloned() { + self.bind(Binding { + name, + kind: Kind::Unknown, + path, + weak: false, + span, + single: false, + aliased: false, + }); + } + } + + fn add_use(&mut self, resolver: &ImportResolver, stmt: &Use, span: (usize, usize)) { + let alias = stmt.alias.as_ref().map(|a| a.name.text.clone()); + let target = + match resolve_use_to_schema(self.project, resolver, &self.namespace, &stmt.path) { + Ok(target) => target, + Err(_) => return self.add_unresolved(stmt, alias, span), + }; + let parts = target.resolved.absolute_namespace.clone(); + let symbols = &target.resolved.symbols; + let item = |name: &str, weak: bool| { + let mut path = parts.clone(); + path.push(name.to_string()); + Binding { + name: name.to_string(), + kind: Kind::Item, + path, + weak, + span, + single: false, + aliased: false, + } + }; + + // `use ns::*`: every name `ns` has, which a declaration or another + // `use` of the name takes precedence over, as in Rust. + if symbols.len() == 1 && symbols[0] == "*" { + match &target.schema { + Some(schema) => { + for name in importable_names(&schema.borrow()) { + let binding = item(&name, true); + self.bind(binding); + } + } + None => self.opaque_glob = true, + } + return; + } + // `use ns::{A, B}`. + if !symbols.is_empty() { + for name in symbols { + let binding = item(name, false); + self.bind(binding); + } + return; + } + + // `use ns`, `use ns::Name`, either `as` an alias, which replaces the + // name. + let Some(last) = parts.last().cloned() else { + return; + }; + let kind = match (&target.schema, target.remaining.is_empty()) { + (Some(_), true) => Kind::Namespace, + (Some(_), false) => Kind::Item, + (None, _) if self.is_namespace(&parts) => Kind::Namespace, + (None, _) => Kind::Unknown, + }; + self.bind(Binding { + name: alias.clone().unwrap_or(last), + kind, + path: parts, + weak: false, + span, + single: true, + aliased: alias.is_some(), + }); + } + + /// A `use` whose path doesn't resolve at all (`parent` from the root): + /// what it names is still brought in, as written. + fn add_unresolved(&mut self, stmt: &Use, alias: Option, span: (usize, usize)) { + let (path, items): (String, Vec) = match &stmt.path { + UsePath::Absolute(path) => (path.text.clone(), vec![]), + UsePath::Relative(rel) => (rel.path.to_string(), vec![]), + UsePath::Multi(multi) => ( + multi.path.to_string(), + multi.items.iter().map(|i| i.text.clone()).collect(), + ), + UsePath::RelativeMulti(multi) => ( + String::new(), + multi.items.iter().map(|i| i.text.clone()).collect(), + ), + UsePath::Glob(_) | UsePath::RelativeGlob(_) => { + self.opaque_glob = true; + return; + } + }; + let parts: Vec = path + .split("::") + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + if items.is_empty() { + if let Some(last) = parts.last().cloned() { + self.bind(Binding { + name: alias.clone().unwrap_or(last), + kind: Kind::Unknown, + path: parts, + weak: false, + span, + single: true, + aliased: alias.is_some(), + }); + } + } + for name in items { + self.bind(Binding { + name, + kind: Kind::Unknown, + path: parts.clone(), + weak: false, + span, + single: false, + aliased: false, + }); + } + } + + /// Whether `parts` is a namespace without a schema of its own: a + /// directory of schemas, `std` or a dependency's name. + fn is_namespace(&self, parts: &[String]) -> bool { + is_namespace(self.project, &self.roots, parts) + } + + /// The schema and declaration the path `path` (a namespace, then a name) + /// names, when the project holds them. + fn locate(&self, path: &[String]) -> Option<(Vec, String)> { + let (schema, remaining) = self.project.find_schema_by_import_namespace_parts(path)?; + match remaining.as_slice() { + [name] => Some((schema.borrow().namespace.clone(), name.clone())), + _ => None, + } + } + + /// The binding of `name` that wins: a strong one before one from a `*`. + fn binding(&self, name: &str, wanted: impl Fn(Kind) -> bool) -> Option<&Binding> { + let mut named = self + .bindings + .iter() + .filter(|b| b.name == name && wanted(b.kind)); + let first = named.next()?; + if !first.weak { + return Some(first); + } + std::iter::once(first) + .chain(named) + .find(|b| !b.weak) + .or(Some(first)) + } + + fn declares(&self, name: &str) -> bool { + self.locals.iter().any(|(declared, _)| declared == name) + } + + /// What `written` names in this schema, or why nothing. + pub fn resolve(&self, written: &str) -> Result { + let segments: Vec<&str> = written.split("::").collect(); + if segments.len() == 1 { + return self.resolve_bare(written); + } + let first = segments[0]; + let mut path: Vec = if let Some(binding) = self.binding(first, |k| k != Kind::Item) + { + binding.path.clone() + } else if self.declares(first) || self.binding(first, |_| true).is_some() { + // A declaration or an item is no qualifier. + return Err(Refusal::QualifierNotInScope); + } else { + match first { + "package" => vec![], + "self" => self.namespace.clone(), + "parent" => { + let mut up = self.namespace.clone(); + up.pop().ok_or(Refusal::QualifierNotInScope)?; + up + } + root if self.roots.contains(root) => vec![root.to_string()], + _ => return Err(Refusal::QualifierNotInScope), + } + }; + path.extend(segments[1..].iter().map(|s| s.to_string())); + let target = self.locate(&path); + // One of this schema's own: it is a declaration here, by its name. + let own = target + .as_ref() + .filter(|(namespace, _)| *namespace == self.namespace) + .map(|(_, name)| name.clone()); + if let Some(name) = own { + return Ok(Resolved { + frozen: name, + target, + }); + } + Ok(Resolved { + frozen: path.join("::"), + target, + }) + } + + fn resolve_bare(&self, name: &str) -> Result { + if self.declares(name) { + return Ok(Resolved { + frozen: name.to_string(), + target: Some((self.namespace.clone(), name.to_string())), + }); + } + if let Some(binding) = self.binding(name, |k| k != Kind::Namespace) { + let target = match binding.kind { + Kind::Item => self.locate(&binding.path), + _ => None, + }; + return Ok(Resolved { + frozen: name.to_string(), + target, + }); + } + if self.binding(name, |_| true).is_some() { + return Err(Refusal::NotInScope { namespace: true }); + } + if self.opaque_glob { + return Ok(Resolved { + frozen: name.to_string(), + target: None, + }); + } + Err(Refusal::NotInScope { namespace: false }) + } + + /// What `written` freezes as, where that is not as written: a qualified + /// name that resolves, as its path. + pub fn frozen(&self, written: &str) -> Option { + if !written.contains("::") { + return None; + } + self.resolve(written) + .ok() + .map(|resolved| resolved.frozen) + .filter(|frozen| frozen != written) + } + + /// Whether `written` names a declaration the project holds. + pub fn exists(&self, written: &str) -> bool { + let Ok(Resolved { + target: Some((namespace, name)), + .. + }) = self.resolve(written) + else { + return false; + }; + self.project.schema_contexts.iter().any(|schema| { + let schema = schema.borrow(); + schema.namespace == namespace && importable_names(&schema).iter().any(|n| *n == name) + }) + } + + /// The schema the type `written` is in scope as names, when it does and + /// the project holds it: where the compile order and the import cycles + /// look for what a schema uses. + pub fn reaches(&self, written: &str) -> Option> { + self.resolve(written) + .ok()? + .target + .map(|(namespace, _)| namespace) + } + + // ---- What a refusal says, and its fix. + + /// How the namespace `namespace` of the project is written from anywhere: + /// the package's own from `package`, `std`'s and a dependency's from their + /// names. + fn absolute(&self, namespace: &[String]) -> String { + match namespace.first() { + Some(first) if self.roots.contains(first) => namespace.join("::"), + _ => std::iter::once("package") + .chain(namespace.iter().map(String::as_str)) + .collect::>() + .join("::"), + } + } + + /// The namespaces of the project's schemas (not this one) that declare a + /// type `name` and end with `qualifier`. + fn declaring(&self, name: &str, qualifier: &[&str]) -> Vec> { + let mut found: Vec> = vec![]; + for schema in &self.project.schema_contexts { + let schema = schema.borrow(); + let namespace = &schema.namespace; + let ends = namespace.len() >= qualifier.len() + && namespace[namespace.len() - qualifier.len()..] + .iter() + .zip(qualifier) + .all(|(a, b)| a.as_str() == *b); + if *namespace != self.namespace + && ends + && declares_type(&schema, name) + && !found.contains(namespace) + { + found.push(namespace.clone()); + } + } + found.sort(); + found + } + + /// How `namespace`'s `name` is written from what is in scope: through the + /// namespace a `use` brought in that it is under, else from its root. + fn written_from_scope(&self, namespace: &[String], name: &str) -> String { + let under = self + .bindings + .iter() + .filter(|b| b.kind == Kind::Namespace && namespace.starts_with(&b.path)) + .max_by_key(|b| b.path.len()); + match under { + Some(binding) => { + let mut parts = vec![binding.name.clone()]; + parts.extend(namespace[binding.path.len()..].iter().cloned()); + parts.push(name.to_string()); + parts.join("::") + } + None => format!("{}::{name}", self.absolute(namespace)), + } + } + + /// The diagnostic for a name written as `written`, at `span` (exactly + /// where `exact`), that `refusal` says nothing resolved. + pub fn diagnostic( + &self, + written: &str, + refusal: Refusal, + span: (usize, usize), + exact: bool, + source: Option<&str>, + ) -> Diagnostic { + match refusal { + Refusal::NotInScope { namespace } => { + self.not_in_scope(written, namespace, span, exact, source) + } + Refusal::QualifierNotInScope => self.qualifier_not_in_scope(written, span, exact), + } + } + + fn not_in_scope( + &self, + name: &str, + namespace: bool, + span: (usize, usize), + _exact: bool, + source: Option<&str>, + ) -> Diagnostic { + let (message, context) = if namespace { + ( + format!("'{name}' is a namespace, not a type"), + format!( + "a `use` brought '{name}' in as a name to qualify with: write `{name}::Type`" + ), + ) + } else { + ( + format!("'{name}' is not in scope"), + format!( + "this schema doesn't declare '{name}', and no `use` of it brings '{name}' in" + ), + ) + }; + let diagnostic = Diagnostic::new(NOT_IN_SCOPE, message) + .with_context(context) + .with_span(span); + if namespace { + return diagnostic; + } + let found = self.declaring(name, &[]); + match found.as_slice() { + [] => diagnostic.with_help(format!( + "no schema of this package or its dependencies declares '{name}'" + )), + [one] => { + let item = format!("{}::{name}", self.absolute(one)); + let qualified = self.written_from_scope(one, name); + let diagnostic = diagnostic.with_help(format!( + "'{name}' is declared in `{}`: add `use {item}`, or write `{qualified}`", + self.absolute(one) + )); + match self.insert_use(&format!("use {item}"), source) { + Some(edit) => diagnostic.with_fix(Fix { + title: format!("Add `use {item}`"), + edits: vec![edit], + }), + None => diagnostic, + } + } + many => diagnostic.with_help(format!( + "'{name}' is declared in {}: add a `use` of the one you mean", + many.iter() + .map(|ns| format!("`{}`", self.absolute(ns))) + .collect::>() + .join(", ") + )), + } + } + + fn qualifier_not_in_scope( + &self, + written: &str, + span: (usize, usize), + exact: bool, + ) -> Diagnostic { + let segments: Vec<&str> = written.split("::").collect(); + let first = segments[0]; + let diagnostic = Diagnostic::new( + QUALIFIER_NOT_IN_SCOPE, + format!("'{first}' is not in scope, in `{written}`"), + ) + .with_context(format!( + "a qualified name starts with a name a `use` brought in, or with `package`, `parent`, `self`, `std` or a dependency's name; '{first}' is none of them" + )) + .with_span(span); + let (name, qualifier) = ( + segments[segments.len() - 1], + &segments[..segments.len() - 1], + ); + let found = self.declaring(name, qualifier); + let [namespace] = found.as_slice() else { + return match found.is_empty() { + true => diagnostic.with_help(format!("nothing declares `{written}`: no schema of this package or its dependencies has a '{name}' under `{}`", qualifier.join("::"))), + false => diagnostic.with_help(format!( + "`{written}` could be {}: write the path from `package` of the one you mean", + found.iter().map(|ns| format!("`{}::{name}`", self.absolute(ns))).collect::>().join(", ") + )), + }; + }; + + // The same item, if a `use` already brings it in by its name. + let mut item = namespace.clone(); + item.push(name.to_string()); + let brought = self + .binding(name, |k| k == Kind::Item) + .filter(|b| b.path == item); + let (write, help) = match brought { + Some(_) => ( + name.to_string(), + format!("`{name}` is in scope already: write `{name}`"), + ), + None => { + let write = self.written_from_scope(namespace, name); + ( + write.clone(), + format!( + "write `{write}`, or add `use {}` to keep `{written}`", + self.absolute(namespace) + ), + ) + } + }; + let diagnostic = diagnostic.with_help(help); + match exact { + true => diagnostic.with_fix(Fix::replace(format!("Write `{write}`"), span, write)), + false => diagnostic, + } + } + + /// The edit that adds the line `text` to the schema's `use`s: after the + /// last of them, else before the first declaration. + fn insert_use(&self, text: &str, source: Option<&str>) -> Option<((usize, usize), String)> { + let source = source?; + if let Some(last) = self.uses.iter().max_by_key(|span| span.1) { + let end = last.0 + source.get(last.0..last.1)?.trim_end().len(); + return Some(((end, end), format!("\n{text}"))); + } + let at = self.first_declaration?; + source.get(..at)?; + Some(((at, at), format!("{text}\n\n"))) + } + + /// Every name defined twice: a `use`d item and a declaration of the same + /// name, or two `use`s of different things that bring in the same name. + /// Two `use`s of the same thing are redundant, not an error, and a name + /// from a `*` gives way to either. + pub fn defined_twice(&self, source: Option<&str>) -> Vec { + enum Site<'a> { + Declaration, + Use(&'a Binding), + } + let mut sites: Vec<(&str, (usize, usize), Site)> = vec![]; + for (name, span) in &self.locals { + sites.push((name.as_str(), *span, Site::Declaration)); + } + for binding in self.bindings.iter().filter(|b| !b.weak) { + sites.push((binding.name.as_str(), binding.span, Site::Use(binding))); + } + sites.sort_by_key(|(_, span, _)| *span); + + let mut names: Vec<&str> = vec![]; + for (name, ..) in &sites { + if !names.contains(name) { + names.push(*name); + } + } + let mut errors = vec![]; + for name in names { + let mut here = sites.iter().filter(|(n, ..)| *n == name); + let Some(first) = here.next() else { continue }; + // The first site that defines the name differently. + let second = here.find(|(_, _, site)| match (&first.2, site) { + (Site::Use(a), Site::Use(b)) => a.path != b.path || a.kind != b.kind, + (Site::Declaration, Site::Declaration) => false, + _ => true, + }); + let Some(second) = second else { continue }; + let what = match (&first.2, &second.2) { + (Site::Use(_), Site::Use(_)) => format!("two `use`s bring in '{name}'"), + _ => format!("a `use` brings in '{name}' and this schema declares it too"), + }; + let mut diagnostic = Diagnostic::new( + DEFINED_TWICE, + format!("'{name}' is defined twice in this schema"), + ) + .with_context(what) + .with_span(second.1) + .with_secondary_span(first.1, "defined here too"); + + // The `use` that can take an alias: the later one, else the other. + let aliasable = [&second.2, &first.2] + .into_iter() + .find_map(|site| match site { + Site::Use(b) if b.single && !b.aliased && b.kind == Kind::Item => Some(*b), + _ => None, + }); + match aliasable { + Some(binding) => { + let alias = alias_for(&binding.path); + let written = format!( + "use {} as {alias}", + self.absolute(&binding.path[..binding.path.len() - 1]) + + "::" + + &binding.path[binding.path.len() - 1] + ); + diagnostic = diagnostic + .with_help(format!("rename one, or import with an alias: `{written}`")); + let taken = sites.iter().any(|(n, ..)| *n == alias); + let end = source + .and_then(|source| source.get(binding.span.0..binding.span.1)) + .map(|text| binding.span.0 + text.trim_end().len()); + if let (false, Some(end)) = (taken, end) { + diagnostic = diagnostic.with_fix(Fix { + title: format!("Import `{name}` as `{alias}`"), + edits: vec![((end, end), format!(" as {alias}"))], + }); + } + } + None => { + diagnostic = diagnostic.with_help( + "rename one, or import with an alias: `use path::Name as OtherName`", + ); + } + } + errors.push(diagnostic); + } + errors + } +} + +/// An alias for an imported item that tells it from another of its name: its +/// first namespace segment in PascalCase, then the name (`billing::api::Invoice` +/// is `BillingInvoice`). +fn alias_for(path: &[String]) -> String { + let Some((name, namespace)) = path.split_last() else { + return String::new(); + }; + let mut alias = String::new(); + if let Some(first) = namespace.first() { + for word in first.split('_').filter(|w| !w.is_empty()) { + let mut chars = word.chars(); + if let Some(c) = chars.next() { + alias.extend(c.to_uppercase()); + alias.push_str(chars.as_str()); + } + } + } + alias.push_str(name); + alias +} + +/// Whether `schema` declares a type `name`. +fn declares_type(schema: &SchemaContext, name: &str) -> bool { + schema.declarations.iter().any(|decl| match &decl.value { + Declaration::Struct(s) => s.name() == name, + Declaration::Enum(e) => e.name() == name, + Declaration::TypeAlias(a) => a.name() == name, + Declaration::Error(e) => e.name() == name, + _ => false, + }) +} + +/// The text of the schema `namespace`, for the fixes: where they edit. +pub fn source_of(project: &ProjectContext, namespace: &[String]) -> Option { + project + .schema_contexts + .iter() + .find(|schema| schema.borrow().namespace == namespace) + .and_then(|schema| { + schema + .borrow() + .codemap + .files() + .first() + .map(|file| file.contents().to_string()) + }) +} + +/// Every name in `declarations` that isn't in scope, and every name defined +/// twice, as errors: all of them, not the first. A dependency's schemas and +/// `std`'s are written against their own packages and were checked when those +/// compiled, so they pass. +pub fn check_references( + declarations: &[rust_sitter::Spanned], + namespace: &[String], + project: &ProjectContext, +) -> Result<(), Vec> { + let scope = Scope::new(declarations, namespace, project); + if namespace + .first() + .is_some_and(|first| scope.roots.contains(first)) + { + return Ok(()); + } + let source = source_of(project, namespace); + let source = source.as_deref(); + + let written = named_types(declarations); + let spans = locate(source, &written); + let mut errors: Vec = written + .iter() + .zip(spans) + .filter_map(|(w, (span, exact))| { + let refusal = scope.resolve(&w.name).err()?; + Some(scope.diagnostic(&w.name, refusal, span, exact, source)) + }) + .collect(); + errors.extend(scope.defined_twice(source)); + errors.sort_by_key(|error| error.span); + if errors.is_empty() { + Ok(()) + } else { + Err(errors) + } +} diff --git a/core/src/schema/ir/frozen/types.rs b/core/src/schema/ir/frozen/types.rs index f0eb649..1471c3a 100644 --- a/core/src/schema/ir/frozen/types.rs +++ b/core/src/schema/ir/frozen/types.rs @@ -236,6 +236,20 @@ impl TypeRef { matches!(self, TypeRef::Array { .. }) } + /// Every name this type is made of, through arrays and unions. + pub fn for_each_name<'a>(&'a self, f: &mut dyn FnMut(&'a str)) { + match self { + TypeRef::Named(name) => f(name), + TypeRef::Array { element, .. } => element.for_each_name(f), + TypeRef::Union(members) => { + for member in members { + member.for_each_name(f); + } + } + TypeRef::Primitive(_) | TypeRef::Unit => {} + } + } + /// `self` with every `Named` part replaced by what `resolve` maps it to /// (`None` keeps it). Used to see through `type` aliases. pub fn map_named(&self, resolve: &mut impl FnMut(&str) -> Option) -> TypeRef { diff --git a/core/src/schema/ir/frozen/unit.rs b/core/src/schema/ir/frozen/unit.rs index b09830c..d78faaf 100644 --- a/core/src/schema/ir/frozen/unit.rs +++ b/core/src/schema/ir/frozen/unit.rs @@ -254,6 +254,80 @@ pub enum FrozenUnit { Unverified(Vec), } +impl FrozenUnit { + /// Every type this unit holds, and the units under it: a field's, a + /// function's arguments and return, an alias's target, a validator's + /// targets and properties, a constant's. + pub fn for_each_type<'a>(&'a self, f: &mut dyn FnMut(&'a TypeRef)) { + match self { + FrozenUnit::Constant { ty, .. } | FrozenUnit::Field { ty, .. } => f(ty), + FrozenUnit::TypeAlias { target, .. } => f(target), + FrozenUnit::Struct { fields, .. } | FrozenUnit::Error { fields, .. } => { + for field in fields { + field.for_each_type(f); + } + } + FrozenUnit::Protocol { functions, .. } => { + for function in functions { + function.for_each_type(f); + } + } + FrozenUnit::Function { arguments, _return, .. } => { + for argument in arguments { + f(&argument.ty); + } + if let Some(ty) = _return { + f(ty); + } + } + FrozenUnit::Validator { properties, targets, .. } => { + for property in properties { + property.for_each_type(f); + } + for target in targets { + f(target); + } + } + _ => {} + } + } + + /// [`for_each_type`](Self::for_each_type), to change them. + pub fn for_each_type_mut(&mut self, f: &mut dyn FnMut(&mut TypeRef)) { + match self { + FrozenUnit::Constant { ty, .. } | FrozenUnit::Field { ty, .. } => f(ty), + FrozenUnit::TypeAlias { target, .. } => f(target), + FrozenUnit::Struct { fields, .. } | FrozenUnit::Error { fields, .. } => { + for field in fields { + field.for_each_type_mut(f); + } + } + FrozenUnit::Protocol { functions, .. } => { + for function in functions { + function.for_each_type_mut(f); + } + } + FrozenUnit::Function { arguments, _return, .. } => { + for argument in arguments { + f(&mut argument.ty); + } + if let Some(ty) = _return { + f(ty); + } + } + FrozenUnit::Validator { properties, targets, .. } => { + for property in properties { + property.for_each_type_mut(f); + } + for target in targets { + f(target); + } + } + _ => {} + } + } +} + /// What an `@key = value` annotation was written as, preserved rather than /// rendered to text. /// diff --git a/core/src/schema/ir/resolve.rs b/core/src/schema/ir/resolve.rs index fcaebc3..01e3105 100644 --- a/core/src/schema/ir/resolve.rs +++ b/core/src/schema/ir/resolve.rs @@ -6,13 +6,29 @@ //! //! 1. a declaration of the schema itself, by its bare name; //! 2. a `use` of the schema: the name it brings in (its alias, else the last -//! segment of its path), or a qualified path that is its path exactly. +//! segment of its path), or a qualified path that is its path exactly; +//! 3. a qualified name, which is a path from the package's root: the schema +//! of that namespace, and its declaration. //! //! There is no suffix match and no taking the first schema that declares the //! name: two schemas that declare `User` are told apart by which of them the -//! schema imports. A name that nothing in the schema brings in is an -//! [`Unresolved`], which a caller that already validated the schema takes for -//! an internal error. +//! schema imports, or by the path it writes. A name that nothing in the +//! schema brings in is an [`Unresolved`], which a caller that already +//! validated the schema takes for an internal error. +//! +//! A qualified name is a path because the compiler froze it as one (core#290): +//! a qualified reference starts with a name a `use` brought into scope, or +//! with a root (`package`, `parent`, `self`, `std`, a dependency's name), and is +//! frozen as the path it resolved to, whichever it was written with. So +//! `api::Invoice` after `use package::billing::api`, an alias's `b::Invoice` +//! and a full `package::billing::api::Invoice` are all +//! `billing::api::Invoice` here. Which names a schema may write is the +//! compiler's rule, `compiler::references`, which refused the others before +//! anything was frozen. This module reads what was frozen, including what an +//! older compiler froze (a dependency's schemas, written when a whole-namespace +//! `use` brought in every name of the schema, are frozen with one import for +//! each), so it is the wider of the two: a name it takes is not always one the +//! compiler would let a schema write now. //! //! The frozen IR holds what this needs: a schema's units are its declarations //! and its `Import`s, each import's path resolved to `namespace::Name` (and the @@ -22,11 +38,6 @@ //! The validator sees one schema at a time, so it asks only what a `use` of //! the schema brings in ([`Import::brings`]); [`Resolver`] goes on to the //! declaration, among the schemas it is given. -//! -//! Qualified references that start with a name a `use` brought into scope -//! (core#290) are this module's to add: `Schema::reach` is where a name is -//! read in its schema, and [`Import::brings`] the rule for what an import is -//! a name for. use std::collections::{HashMap, HashSet}; @@ -67,7 +78,9 @@ impl<'a> Import<'a> { } /// Whether a name written in the schema is this import's: the name it - /// brings in, or its path written out. + /// brings in, or its path written out. Reading the frozen IR, so it takes + /// what any compiler froze; the Rust model's rule for what a schema may + /// write is `compiler::references`'s. pub fn brings(&self, name: &str) -> bool { self.bare() == Some(name) || self.path == name } @@ -113,18 +126,20 @@ pub struct Found<'a> { } /// Why a name resolved to no declaration. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Unresolved<'a> { - /// Nothing the schema declares and no `use` of it brings the name in. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Unresolved { + /// Nothing the schema declares and no `use` of it brings the name in, and + /// it is no path. NotInScope, - /// A `use` brings it in, from a schema that wasn't given: a dependency's - /// own dependency, which what a dependency publishes doesn't hold. - NotLoaded(&'a str), + /// The name is a path (a `use`'s, or a qualified name's) into a schema + /// that wasn't given: a dependency's own dependency, which what a + /// dependency publishes doesn't hold. + NotLoaded(String), /// It is declared (or brought in), but not a type: a protocol, a /// constant, a validator, a namespace. NotAType, - /// A `use` brings it in from a schema that declares nothing of the name. - NotDeclared(&'a str), + /// The path is into a schema that declares nothing of the name. + NotDeclared(String), } /// The schemas a name can be resolved among, each as its units: the @@ -147,14 +162,18 @@ struct Schema<'a> { impl<'a> Schema<'a> { /// What the name `name`, written in this schema, points at on its own: - /// one of its declarations, or the path a `use` of it brings in. `None` - /// where neither does. + /// one of its declarations, the path a `use` of it brings in, or, for a + /// qualified name no `use` is the path of, the path it is. `None` for a + /// bare name that none of those is. fn reach(&self, name: &str) -> Option> { if let Some(unit) = self.declared.get(name) { return Some(Reach::Declared(unit)); } let imports: Vec<&Import<'a>> = self.imports.iter().filter(|i| i.brings(name)).collect(); - (!imports.is_empty()).then_some(Reach::Imported(imports)) + if !imports.is_empty() { + return Some(Reach::Imported(imports)); + } + name.contains("::").then_some(Reach::Path) } } @@ -163,6 +182,9 @@ enum Reach<'a, 's> { Declared(&'a FrozenUnit), /// Each `use` that brings it in, in order. Imported(Vec<&'s Import<'a>>), + /// A qualified name, which is the path of its declaration from the + /// package's root. + Path, } impl<'a> Resolver<'a> { @@ -226,11 +248,12 @@ impl<'a> Resolver<'a> { /// The declaration `name` names, written in the schema `from`: the one /// the validator accepted it for. - pub fn resolve(&self, from: usize, name: &str) -> Result, Unresolved<'a>> { + pub fn resolve(&self, from: usize, name: &str) -> Result, Unresolved> { let schema = &self.schemas[from]; match schema.reach(name).ok_or(Unresolved::NotInScope)? { Reach::Declared(unit) if is_type(unit) => Ok(Found { schema: from, unit }), Reach::Declared(_) => Err(Unresolved::NotAType), + Reach::Path => self.locate(schema, name), // The first of the `use`s that brings the name in and leads to a // declaration; where none does, why the first didn't. Reach::Imported(imports) => { @@ -250,7 +273,7 @@ impl<'a> Resolver<'a> { /// The declaration the path `namespace::Name` of a `use` in `schema` /// names. - fn locate(&self, schema: &Schema<'a>, path: &'a str) -> Result, Unresolved<'a>> { + fn locate(&self, schema: &Schema<'a>, path: &str) -> Result, Unresolved> { let Some((namespace, name)) = path.rsplit_once("::") else { return Err(Unresolved::NotAType); }; @@ -272,11 +295,11 @@ impl<'a> Resolver<'a> { } None => self.scope_of(namespace), }; - let at = at.ok_or(Unresolved::NotLoaded(path))?; + let at = at.ok_or_else(|| Unresolved::NotLoaded(path.to_string()))?; match self.schemas[at].declared.get(name) { Some(unit) if is_type(unit) => Ok(Found { schema: at, unit }), Some(_) => Err(Unresolved::NotAType), - None => Err(Unresolved::NotDeclared(path)), + None => Err(Unresolved::NotDeclared(path.to_string())), } } } @@ -310,7 +333,7 @@ mod tests { schemas: &'a [Vec], from: &str, name: &str, - ) -> Result<&'a str, Unresolved<'a>> { + ) -> Result<&'a str, Unresolved> { let from = resolver.scope_of(from).unwrap(); let found = resolver.resolve(from, name)?; Ok(schema_namespace(&schemas[found.schema]).unwrap()) @@ -356,16 +379,27 @@ mod tests { let resolver = Resolver::new(schemas.iter().map(Vec::as_slice), Vec::::new()); let at = |name| namespace_of(&resolver, &schemas, "app", name); // `api::User` is a path no schema has: not `rapi`'s, not `v1::api`'s. - assert_eq!(at("User"), Err(Unresolved::NotLoaded("api::User"))); - assert_eq!(at("api::User"), Err(Unresolved::NotLoaded("api::User"))); - // Not through the schema's imports: not in scope, whatever declares it. - assert_eq!(at("v1::api::User"), Err(Unresolved::NotInScope)); + assert_eq!(at("User"), Err(Unresolved::NotLoaded("api::User".into()))); + assert_eq!( + at("api::User"), + Err(Unresolved::NotLoaded("api::User".into())) + ); + // A full path is the schema of that namespace, which an import of + // the schema isn't needed for: `v1::api`, not `rapi` or `api`. + assert_eq!(at("v1::api::User"), Ok("v1::api")); + assert_eq!(at("rapi::User"), Ok("rapi")); + // A bare name that nothing brings in is not in scope, whatever + // declares it. assert_eq!(at("Other"), Err(Unresolved::NotInScope)); assert_eq!(at("api"), Err(Unresolved::NotInScope)); } + /// A schema that declares what a `use` of it brings in is one the compiler + /// refuses (`reference::defined-twice`, core#290), so it is never frozen. + /// A resolver handed one anyway (a dependency's IR from before the rule) + /// reads the declaration: the name is the schema's own. #[test] - fn a_declaration_shadows_an_import_of_its_name() { + fn a_declaration_is_preferred_to_an_import_of_its_name() { let schemas = vec![ schema("other", vec![unit("User")]), schema("app", vec![import("other::User", None), unit("User")]), @@ -374,6 +408,33 @@ mod tests { assert_eq!(namespace_of(&resolver, &schemas, "app", "User"), Ok("app")); } + #[test] + fn a_qualified_name_is_the_path_it_is() { + let schemas = vec![ + schema("billing::api", vec![unit("Invoice")]), + schema("archive", vec![unit("Invoice")]), + // Frozen as `billing::api::Invoice` whichever way it was written: + // after `use package::billing::api` as `api::Invoice`, after + // `use package::billing` as `billing::api::Invoice`, as + // `package::billing::api::Invoice` with no `use`, or `b::Invoice`. + schema("app", vec![import("billing::api", None), unit("Own")]), + ]; + let resolver = Resolver::new(schemas.iter().map(Vec::as_slice), Vec::::new()); + let at = |name| namespace_of(&resolver, &schemas, "app", name); + assert_eq!(at("billing::api::Invoice"), Ok("billing::api")); + assert_eq!(at("archive::Invoice"), Ok("archive"), "no import of it"); + assert_eq!( + at("billing::api::Gone"), + Err(Unresolved::NotDeclared("billing::api::Gone".into())) + ); + assert_eq!( + at("billing::nowhere::Invoice"), + Err(Unresolved::NotLoaded("billing::nowhere::Invoice".into())) + ); + // A bare name is still what the schema declares or imports, nothing else. + assert_eq!(at("Invoice"), Err(Unresolved::NotInScope)); + } + #[test] fn what_is_no_type_is_said_so() { let constant = FrozenUnit::Constant { @@ -397,7 +458,10 @@ mod tests { let resolver = Resolver::new(schemas.iter().map(Vec::as_slice), Vec::::new()); let at = |name| namespace_of(&resolver, &schemas, "app", name); assert_eq!(at("LIMIT"), Err(Unresolved::NotAType)); - assert_eq!(at("Gone"), Err(Unresolved::NotDeclared("limits::Gone"))); + assert_eq!( + at("Gone"), + Err(Unresolved::NotDeclared("limits::Gone".into())) + ); assert_eq!(at("limits"), Err(Unresolved::NotAType)); } @@ -427,7 +491,7 @@ mod tests { assert_eq!(at("s0::A"), Ok("p0::s0")); assert_eq!(at("Request"), Ok("std::http"), "std, as written"); // A package of its own that the consumer doesn't hold isn't guessed at. - assert_eq!(at("Gone"), Err(Unresolved::NotLoaded("base::Gone"))); + assert_eq!(at("Gone"), Err(Unresolved::NotLoaded("base::Gone".into()))); assert!(resolver.is_other_package(resolver.scope_of("p0::s1").unwrap())); assert!(!resolver.is_other_package(resolver.scope_of("s0").unwrap())); } diff --git a/core/src/schema/ir/validation/validator.rs b/core/src/schema/ir/validation/validator.rs index b26d41b..a689519 100644 --- a/core/src/schema/ir/validation/validator.rs +++ b/core/src/schema/ir/validation/validator.rs @@ -118,6 +118,15 @@ const UNVERIFIED_VERSION_HONESTY: DiagnosticCode = /// Types come back already resolved through aliases in the schema that /// declares them. pub trait ImportLookup { + /// Whether the qualified name `name`, written as a type, is a path to a + /// declaration the project holds: `billing::api::Invoice`, which a + /// schema's `use package::billing` makes it write that way, or a full path + /// from a root with no `use` at all (core#290). A qualified type freezes as + /// its path from the package's root, so the schema needn't import it. + /// `false` when the lookup can't say. + fn reaches(&self, _name: &str) -> bool { + false + } /// The `for` targets of an imported validator, as written or qualified /// (`StringBounds`, `validators::StringBounds`). fn validator_targets(&self, name: &str) -> Option>; @@ -291,6 +300,24 @@ pub fn validate_with( } } + // A qualified type that a `use` doesn't bring in whole is a path the + // project can reach on its own: an import of the schema, for what follows. + let mut paths: Vec<&str> = vec![]; + for unit in units { + unit.for_each_type(&mut |ty| { + ty.for_each_name(&mut |name| { + if name.contains("::") { + paths.push(name); + } + }) + }); + } + for name in paths { + if symbols.get(name).is_none() && imports.reaches(name) { + let _ = symbols.insert(name, SymbolType::Import, None); + } + } + // Stop if duplicate errors found (avoids cascading errors) if !errors.is_empty() { return Err(errors); diff --git a/core/tests/schema/ir/imports.rs b/core/tests/schema/ir/imports.rs index 5b5295c..98c6566 100644 --- a/core/tests/schema/ir/imports.rs +++ b/core/tests/schema/ir/imports.rs @@ -190,7 +190,8 @@ fn test_unknown_namespace_is_rejected_with_a_suggestion() { let error = interpret_context(&project).expect_err("an unresolved import should fail").to_string(); assert!(error.contains("no schema in this package or its dependencies matches 'typse::User'"), "{error}"); - assert!(error.contains("did you mean 'types'?"), "{error}"); + // One of the package's own schemas, so the path that reaches it (core#286). + assert!(error.contains("did you mean 'package::types::User'?"), "{error}"); } #[test] @@ -345,6 +346,57 @@ fn test_a_declared_dependency_without_merged_schemas_is_unresolved() { assert!(error.contains("Unresolved import"), "{error}"); } +#[test] +fn test_a_typo_in_an_own_schemas_name_suggests_the_path_that_reaches_it() { + // core#286: one of the package's own schemas is reached through `package::`, + // so the suggestion, and its fix, say so and don't lead to the next error. + let cases = [ + ("use typse::User\n\nstruct R {\n u: User\n}\n", "package::types::User", "use package::types::User\n\nstruct R {\n u: User\n}\n"), + ("use typse::*\n\nstruct R {\n u: User\n}\n", "package::types::*", "use package::types::*\n\nstruct R {\n u: User\n}\n"), + ( + "use typse::{User, Post}\n\nstruct R {\n u: User\n}\n", + "package::types::{User, Post}", + "use package::types::{User, Post}\n\nstruct R {\n u: User\n}\n", + ), + ( + "use typse::User as Account\n\nstruct R {\n u: Account\n}\n", + "package::types::User", + "use package::types::User as Account\n\nstruct R {\n u: Account\n}\n", + ), + ("use typse\n\nstruct R {\n u: types::User\n}\n", "package::types", "use package::types\n\nstruct R {\n u: types::User\n}\n"), + ]; + for (source, suggested, fixed) in cases { + let mut project = build_project(); + add_schema(&mut project, &["types"], TYPES); + add_schema(&mut project, &["api"], source); + + let errors = bare_path_errors(&project, &["api"]); + assert_eq!(errors.len(), 1, "{source}: {errors:?}"); + assert!(errors[0].context.contains(&format!("did you mean '{suggested}'?")), "{source}: {}", errors[0].context); + let fix = errors[0].fix.as_ref().unwrap_or_else(|| panic!("{source}: no fix")); + assert_eq!(fix.title, format!("Write `{suggested}`"), "{source}"); + assert_eq!(fix.apply(source), fixed, "{source}"); + + // What the fix writes builds. + let mut project = build_project(); + add_schema(&mut project, &["types"], TYPES); + add_schema(&mut project, &["api"], fixed); + assert!(bare_path_errors(&project, &["api"]).is_empty(), "{fixed}"); + interpret_context(&project).unwrap_or_else(|e| panic!("{fixed}: {e}")); + } +} + +#[test] +fn test_a_typo_in_a_dependency_name_stays_absolute_and_has_no_package_fix() { + let mut project = build_project_with_dependency(); + add_schema(&mut project, &["api"], "use shard::models::Thing\n\nstruct R {\n t: Thing\n}\n"); + let errors = bare_path_errors(&project, &["api"]); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert!(errors[0].context.contains("did you mean 'shared'?"), "{}", errors[0].context); + assert!(!errors[0].context.contains("package::"), "{}", errors[0].context); + assert!(errors[0].fix.is_none()); +} + #[test] fn test_a_typo_in_a_dependency_name_is_rejected_with_a_suggestion() { let mut project = build_project_with_dependency(); @@ -382,17 +434,19 @@ fn test_whole_namespace_import_allows_qualified_field_reference() { } #[test] -fn test_glob_import_allows_qualified_field_reference() { +fn test_glob_import_allows_the_bare_field_reference() { + // A glob brings in the names of the namespace, not the namespace (core#290): + // this was `user: types::User`, which is `reference::qualifier-not-in-scope`. let mut project = build_project(); add_schema(&mut project, &["types"], "struct User {\n id: u64\n}\n"); add_schema( &mut project, &["api"], - "use package::types::*\n\nstruct Response {\n user: types::User\n}\n", + "use package::types::*\n\nstruct Response {\n user: User\n}\n", ); interpret_context(&project).expect( - "a field qualified with a glob-imported namespace should resolve, now that glob \ + "a field named by a glob-imported name should resolve, now that glob \ imports expand into per-symbol Import units", ); } @@ -631,7 +685,7 @@ fn test_cross_file_type_alias_keeps_its_name_via_single_symbol_use() { } #[test] -fn test_cross_file_type_alias_keeps_its_name_via_whole_namespace_use() { +fn test_cross_file_type_alias_keeps_its_name_via_the_use_of_it() { use comline_core::schema::ir::frozen::types::TypeRef; let mut project = build_project(); @@ -639,9 +693,9 @@ fn test_cross_file_type_alias_keeps_its_name_via_whole_namespace_use() { add_schema( &mut project, &["api"], - // bare `id: UserId`, not `id: types::UserId` - exercises the - // `declared_symbol_names` whole-namespace expansion path. - "use package::types\n\nstruct Response {\n id: UserId\n}\n", + // Was `use package::types` with a bare `id: UserId`, which brings in + // only `types` now (core#290): the `use` names the alias. + "use package::types::UserId\n\nstruct Response {\n id: UserId\n}\n", ); interpret_context(&project).expect("compilation should succeed"); diff --git a/core/tests/schema/ir/mod.rs b/core/tests/schema/ir/mod.rs index 0b6da95..59165ac 100644 --- a/core/tests/schema/ir/mod.rs +++ b/core/tests/schema/ir/mod.rs @@ -12,3 +12,4 @@ pub mod dataless_arrays; pub mod compat_rules; pub mod bounds; pub mod type_resolution; +pub mod references; diff --git a/core/tests/schema/ir/references.rs b/core/tests/schema/ir/references.rs new file mode 100644 index 0000000..05b5642 --- /dev/null +++ b/core/tests/schema/ir/references.rs @@ -0,0 +1,496 @@ +// What a type written in a schema names: the Rust model (core#290). A name in +// scope is a declaration of the schema, what a `use` brings in (its alias, else +// its last segment) or a root; a whole-namespace `use` brings in only its name; +// a qualified reference starts with a name in scope or a root, and freezes as +// its path from the package's root. The specification's `references` cases hold +// the outcomes (`package/compiler_cases.rs`); these hold what they don't say: +// the diagnostics' fixes, every error at once, and what freezes. + +use comline_core::diagnostics::Diagnostic; +use comline_core::package::build::PackageSources; +use comline_core::package::config::idl::grammar as config_grammar; +use comline_core::package::config::ir::compiler::interpret::interpret_context; +use comline_core::package::config::ir::context::ProjectContext; +use comline_core::schema::idl::grammar; +use comline_core::schema::ir::compiler::references::{ + check_references, DEFINED_TWICE, NOT_IN_SCOPE, QUALIFIER_NOT_IN_SCOPE, +}; +use comline_core::schema::ir::context::SchemaContext; +use comline_core::schema::ir::frozen::types::TypeRef; +use comline_core::schema::ir::frozen::unit::FrozenUnit; +use comline_core::utils::codemap::CodeMap; + +use std::cell::RefCell; +use std::rc::Rc; + +fn build_project() -> ProjectContext { + let congregation = config_grammar::parse("congregation test\nspecification_version = 1") + .expect("congregation should parse"); + ProjectContext::with_config(congregation) +} + +fn add_schema(project: &mut ProjectContext, namespace: &[&str], source: &str) { + let document = grammar::parse(source).expect("schema should parse"); + let mut codemap = CodeMap::new(); + codemap.insert_file(namespace.join("/"), source.to_string()); + let namespace: Vec = namespace.iter().map(|s| s.to_string()).collect(); + let context = SchemaContext::with_declarations(document.0, namespace, codemap); + project.schema_contexts.push(Rc::new(RefCell::new(context))); +} + +/// What the reference check says of the schema `namespace`. +fn errors(project: &ProjectContext, namespace: &[&str]) -> Vec { + let namespace: Vec = namespace.iter().map(|s| s.to_string()).collect(); + let declarations = project + .schema_contexts + .iter() + .find(|schema| schema.borrow().namespace == namespace) + .expect("schema should exist") + .borrow() + .declarations + .clone(); + check_references(&declarations, &namespace, project) + .err() + .unwrap_or_default() +} + +const TYPES: &str = "struct User {\n id: u64\n}\n\nstruct Order {\n id: u64\n}\n"; +const INVOICE: &str = "struct Invoice {\n data: char[max 64]\n}\n"; + +/// A project of `types` and what `api` is, and the check's errors for `api`. +fn api_errors(api: &str) -> Vec { + let mut project = build_project(); + add_schema(&mut project, &["types"], TYPES); + add_schema(&mut project, &["api"], api); + errors(&project, &["api"]) +} + +/// `api` as `api` is after the one fix of the one error it has. +fn fixed(api: &str) -> String { + let errors = api_errors(api); + assert_eq!(errors.len(), 1, "{api}: {errors:?}"); + errors[0] + .fix + .as_ref() + .unwrap_or_else(|| panic!("{api}: no fix")) + .apply(api) +} + +fn compile(schemas: &[(&[&str], &str)]) -> Result { + let mut sources = PackageSources::new(); + for (namespace, source) in schemas { + sources = sources.schema(namespace.iter().copied(), source.to_string()); + } + sources.compile().map_err(|e| e.to_string()) +} + +/// The type of the first field of the struct `A` in the schema `namespace`. +fn field_of_a(project: &ProjectContext, namespace: &str) -> TypeRef { + let schema = project + .schema_contexts + .iter() + .find(|s| s.borrow().namespace_joined() == namespace) + .expect("schema should exist"); + let frozen = schema + .borrow() + .frozen_schema + .borrow() + .clone() + .expect("frozen"); + frozen + .iter() + .find_map(|unit| match unit { + FrozenUnit::Struct { name, fields, .. } if name == "A" => match &fields[0] { + FrozenUnit::Field { ty, .. } => Some(ty.clone()), + _ => None, + }, + _ => None, + }) + .expect("struct A") +} + +// ---- What a `use` brings into scope. + +#[test] +fn a_whole_namespace_use_brings_in_only_its_name() { + let api = "use package::types\n\nstruct A {\n user: User\n}\n"; + let errors = api_errors(api); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].code, NOT_IN_SCOPE); + assert_eq!(errors[0].code.id, "reference::not-in-scope"); + assert_eq!(errors[0].message, "'User' is not in scope"); + let help = errors[0].help.as_deref().unwrap(); + assert!(help.contains("add `use package::types::User`"), "{help}"); + assert!(help.contains("write `types::User`"), "{help}"); + + // The fix adds the `use` that names it, and then it builds. + let fix = errors[0].fix.as_ref().unwrap(); + assert_eq!(fix.title, "Add `use package::types::User`"); + let with_use = fix.apply(api); + assert_eq!( + with_use, + "use package::types\nuse package::types::User\n\nstruct A {\n user: User\n}\n" + ); + compile(&[(&["types"], TYPES), (&["api"], &with_use)]).expect("what the fix writes builds"); + // So does writing it qualified. + compile(&[ + (&["types"], TYPES), + ( + &["api"], + "use package::types\n\nstruct A {\n user: types::User\n}\n", + ), + ]) + .expect("a qualified name builds"); +} + +#[test] +fn a_name_nothing_declares_has_no_fix_that_adds_a_use() { + for api in [ + "use package::types\n\nstruct A {\n user: Nowhere\n}\n", + "struct A {\n user: nope::types::User\n}\n", + ] { + let errors = api_errors(api); + assert_eq!(errors.len(), 1, "{api}: {errors:?}"); + assert!(errors[0].fix.is_none(), "{api}: {:?}", errors[0].fix); + } + let errors = api_errors("struct A {\n user: nope::types::User\n}\n"); + assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE); + assert_eq!(errors[0].code.id, "reference::qualifier-not-in-scope"); +} + +#[test] +fn an_alias_replaces_the_name() { + let api = "use package::types as t\n\nstruct A {\n user: types::User\n}\n"; + let errors = api_errors(api); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE); + assert_eq!( + fixed(api), + "use package::types as t\n\nstruct A {\n user: t::User\n}\n", + "the alias is what comes into scope" + ); +} + +#[test] +fn an_item_or_a_list_does_not_bring_in_its_namespace() { + for api in [ + "use package::types::User\n\nstruct A {\n user: types::User\n}\n", + "use package::types::{User, Order}\n\nstruct A {\n user: types::User\n}\n", + "use package::types::*\n\nstruct A {\n user: types::User\n}\n", + ] { + let errors = api_errors(api); + assert_eq!(errors.len(), 1, "{api}: {errors:?}"); + assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE, "{api}"); + // `User` is in scope already, so that is what to write. + assert_eq!( + fixed(api), + api.replace("types::User\n}", "User\n}"), + "{api}" + ); + assert!( + errors[0].help.as_deref().unwrap().contains("write `User`"), + "{api}" + ); + } +} + +#[test] +fn a_qualifier_is_a_root_or_a_name_in_scope() { + // No `use`: `types` is a schema, not a name in scope. The fixes write + // the path from `package`. + let api = "struct A {\n user: types::User\n}\n"; + let errors = api_errors(api); + assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE); + assert_eq!( + fixed(api), + "struct A {\n user: package::types::User\n}\n" + ); + assert_eq!( + fixed("struct A {\n user: User\n}\n"), + "use package::types::User\n\nstruct A {\n user: User\n}\n", + "with no `use` at all, the fix is put before the first declaration" + ); + + // A segment skipped: `api` is under `billing`, which is in scope. + let mut project = build_project(); + add_schema(&mut project, &["billing", "api"], INVOICE); + let skipping = "use package::billing\n\nstruct A {\n i: api::Invoice\n}\n"; + add_schema(&mut project, &["app"], skipping); + let errors = errors(&project, &["app"]); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE); + assert_eq!( + errors[0].fix.as_ref().unwrap().apply(skipping), + "use package::billing\n\nstruct A {\n i: billing::api::Invoice\n}\n" + ); +} + +// ---- A name defined twice. + +#[test] +fn a_declaration_and_a_use_of_one_name_is_defined_twice() { + let mut project = build_project(); + add_schema(&mut project, &["billing", "api"], INVOICE); + let api = "use package::billing::api::Invoice\n\nstruct Invoice {\n data: char[max 64]\n}\n"; + add_schema(&mut project, &["api"], api); + + let errors = errors(&project, &["api"]); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].code, DEFINED_TWICE); + assert_eq!(errors[0].code.id, "reference::defined-twice"); + assert_eq!( + errors[0].message, + "'Invoice' is defined twice in this schema" + ); + assert!( + errors[0].secondary.is_some(), + "the other place is shown too" + ); + let aliased = errors[0].fix.as_ref().unwrap().apply(api); + assert_eq!( + aliased, + "use package::billing::api::Invoice as BillingInvoice\n\nstruct Invoice {\n data: char[max 64]\n}\n" + ); + compile(&[(&["billing", "api"], INVOICE), (&["api"], &aliased)]) + .expect("an alias defines each name once"); +} + +#[test] +fn two_uses_of_one_name_are_defined_twice_and_the_same_use_twice_is_not() { + let mut project = build_project(); + add_schema(&mut project, &["a"], TYPES); + add_schema(&mut project, &["b"], TYPES); + let api = "use package::a::User\nuse package::b::User\n\nstruct A {\n id: u64\n}\n"; + add_schema(&mut project, &["api"], api); + let errors = errors(&project, &["api"]); + assert_eq!(errors.len(), 1, "{errors:?}"); + assert_eq!(errors[0].code, DEFINED_TWICE); + // The later `use` takes the alias. + assert_eq!( + errors[0].fix.as_ref().unwrap().apply(api), + "use package::a::User\nuse package::b::User as BUser\n\nstruct A {\n id: u64\n}\n" + ); + + // The same thing brought in twice is redundant, not an error; and a name + // from a `*` gives way to a declaration or a `use` of it. + for api in [ + "use package::a::User\nuse package::a::User\n\nstruct A {\n u: User\n}\n", + "use package::a::*\n\nstruct User {\n id: u8\n}\n\nstruct A {\n u: User\n}\n", + "use package::a::*\nuse package::b::User\n\nstruct A {\n u: User\n}\n", + ] { + let mut project = build_project(); + add_schema(&mut project, &["a"], TYPES); + add_schema(&mut project, &["b"], TYPES); + add_schema(&mut project, &["api"], api); + assert!( + errors_of(&project).is_empty(), + "{api}: {:?}", + errors_of(&project) + ); + } + + fn errors_of(project: &ProjectContext) -> Vec { + errors(project, &["api"]) + } +} + +// ---- Every error is reported; an import that fails brings its name in. + +#[test] +fn every_error_is_reported_not_the_first() { + let mut project = build_project(); + add_schema(&mut project, &["types"], TYPES); + let api = "use package::types\n\nstruct User {\n id: u8\n}\n\nstruct A {\n first: Order\n second: nope::User\n third: types::Order\n}\n"; + add_schema(&mut project, &["api"], api); + let errors = errors(&project, &["api"]); + let codes: Vec<&str> = errors.iter().map(|e| e.code.id).collect(); + assert_eq!( + codes, + [ + "reference::not-in-scope", + "reference::qualifier-not-in-scope" + ], + "{errors:?}" + ); + // The errors point at the names, in the order written. + let at = |error: &Diagnostic| { + let (start, end) = error.span.unwrap(); + &api[start..end] + }; + assert_eq!((at(&errors[0]), at(&errors[1])), ("Order", "nope::User")); +} + +#[test] +fn an_import_and_a_reference_are_both_reported_by_the_build() { + let error = compile(&[ + (&["models"], TYPES), + (&["api"], "use models\n\nstruct A {\n u: User\n}\n"), + ]) + .err() + .expect("both are errors"); + assert!(error.contains("import::bare-own-schema-path"), "{error}"); + assert!(error.contains("reference::not-in-scope"), "{error}"); +} + +#[test] +fn a_use_that_fails_to_resolve_still_brings_its_name_in() { + let mut project = build_project(); + add_schema(&mut project, &["models"], TYPES); + add_schema( + &mut project, + &["api"], + "use modles::User\n\nstruct A {\n u: User\n}\n", + ); + assert!(errors(&project, &["api"]).is_empty()); + let error = compile(&[ + (&["models"], TYPES), + (&["api"], "use modles::User\n\nstruct A {\n u: User\n}\n"), + ]) + .err() + .expect("the import is the one error"); + assert!( + error.contains("import::unresolved") && !error.contains("reference::"), + "{error}" + ); +} + +// ---- What a qualified reference freezes as. + +#[test] +fn a_qualified_reference_freezes_as_its_resolved_path() { + let spellings = [ + "use package::billing::api\n\nstruct A {\n i: api::Invoice\n}\n", + "use package::billing\n\nstruct A {\n i: billing::api::Invoice\n}\n", + "use package::billing as b\n\nstruct A {\n i: b::api::Invoice\n}\n", + "use package::billing::api as b\n\nstruct A {\n i: b::Invoice\n}\n", + "struct A {\n i: package::billing::api::Invoice\n}\n", + ]; + for api in spellings { + let project = compile(&[(&["billing", "api"], INVOICE), (&["app"], api)]) + .unwrap_or_else(|e| panic!("{api}: {e}")); + assert_eq!( + field_of_a(&project, "app"), + TypeRef::Named("billing::api::Invoice".into()), + "{api}" + ); + } + + // A bare name, and a qualified one that is already a path, are as written. + let project = compile(&[ + (&["billing", "api"], INVOICE), + ( + &["app"], + "use package::billing::api::Invoice\n\nstruct A {\n i: Invoice\n}\n", + ), + ]) + .unwrap(); + assert_eq!( + field_of_a(&project, "app"), + TypeRef::Named("Invoice".into()) + ); + let project = compile(&[ + (&["types"], TYPES), + ( + &["app"], + "use package::types\n\nstruct A {\n u: types::User\n}\n", + ), + ]) + .unwrap(); + assert_eq!( + field_of_a(&project, "app"), + TypeRef::Named("types::User".into()) + ); +} + +#[test] +fn what_is_written_the_same_gives_the_same_frozen_schema_whichever_the_spelling() { + // The spans differ with the text, so only what the names freeze as is held. + let frozen = |api: &str| { + let project = compile(&[(&["billing", "api"], INVOICE), (&["app"], api)]).unwrap(); + field_of_a(&project, "app").to_string() + }; + assert_eq!( + frozen("use package::billing::api\n\nstruct A {\n i: api::Invoice[]\n}\n"), + frozen("struct A {\n i: package::billing::api::Invoice[]\n}\n"), + ); +} + +#[test] +fn a_full_path_from_a_root_needs_no_use() { + let shapes = [ + (&["shapes", "types"][..], TYPES), + ( + &["shapes", "api"][..], + "struct A {\n u: package::shapes::types::User\n p: parent::types::Order\n}\n", + ), + ]; + let project = compile(&shapes).expect("package:: and parent::"); + assert_eq!( + field_of_a(&project, "shapes::api"), + TypeRef::Named("shapes::types::User".into()) + ); + + let nested = [ + (&["api"][..], "struct A {\n u: self::nested::User\n}\n"), + (&["api", "nested"][..], TYPES), + ]; + let project = compile(&nested).expect("self::"); + assert_eq!( + field_of_a(&project, "api"), + TypeRef::Named("api::nested::User".into()) + ); + + let std = [(&["api"][..], "struct A {\n r: std::http::Request\n}\n")]; + let project = compile(&std).expect("std:: merges the schema it names, with no use"); + assert_eq!( + field_of_a(&project, "api"), + TypeRef::Named("std::http::Request".into()) + ); +} + +#[test] +fn an_alias_target_and_a_function_read_qualified_names_too() { + let api = "use package::billing\n\ntype Id = billing::api::Invoice\n\nprotocol P {\n function get(i: billing::api::Invoice) -> Id;\n}\n"; + let project = compile(&[(&["billing", "api"], INVOICE), (&["app"], api)]).expect("builds"); + let schema = project + .schema_contexts + .iter() + .find(|s| s.borrow().namespace_joined() == "app") + .unwrap(); + let frozen = schema.borrow().frozen_schema.borrow().clone().unwrap(); + let alias = frozen.iter().find_map(|u| match u { + FrozenUnit::TypeAlias { target, .. } => Some(target.clone()), + _ => None, + }); + assert_eq!(alias, Some(TypeRef::Named("billing::api::Invoice".into()))); +} + +// ---- A package written before the rule freezes as it did. + +#[test] +fn a_whole_namespace_use_and_a_qualified_name_freeze_as_they_always_did() { + let project = compile(&[ + (&["types"], TYPES), + ( + &["api"], + "use package::types\n\nstruct A {\n user: types::User\n}\n", + ), + ]) + .unwrap(); + let schema = project + .schema_contexts + .iter() + .find(|s| s.borrow().namespace_joined() == "api") + .unwrap(); + let frozen = schema.borrow().frozen_schema.borrow().clone().unwrap(); + let imports: Vec<&str> = frozen + .iter() + .filter_map(|u| match u { + FrozenUnit::Import(path, _, _) => Some(path.as_str()), + _ => None, + }) + .collect(); + // The import is still one per name the namespace has: what is frozen is + // what it was, whatever the file may now write. + assert_eq!(imports, ["types", "types::User", "types::Order"]); +} diff --git a/core/tests/schema/ir/type_resolution.rs b/core/tests/schema/ir/type_resolution.rs index ad8c1b5..e452394 100644 --- a/core/tests/schema/ir/type_resolution.rs +++ b/core/tests/schema/ir/type_resolution.rs @@ -104,34 +104,47 @@ fn a_name_resolves_to_the_declaration_the_schema_imports() { pair[imported].join("::"), if imported == 0 { &big } else { &small }, ); + // What is written, and what it freezes as: a qualified name is + // frozen as its path from the package's root (core#290), however + // it was written. let forms = [ ( "bare", format!("use package::{path}::User"), "User".to_string(), + "User".to_string(), ), ( "aliased", format!("use package::{path}::User as Account"), "Account".to_string(), + "Account".to_string(), ), ( "qualified", format!("use package::{path}::User"), + format!("package::{path}::User"), + format!("{path}::User"), + ), + ( + "qualified by a namespace", + format!("use package::{path}"), + format!("{}::User", pair[imported].last().unwrap()), format!("{path}::User"), ), ]; - for (form, use_line, reference) in forms { + for (form, use_line, written, reference) in forms { + let reference = reference.as_str(); let context = compile(&[ (pair[0], BIG.to_string()), (pair[1], SMALL.to_string()), - (&["app"], users(&use_line, &reference)), + (&["app"], users(&use_line, &written)), ]); let shape = shape(&context, "Users"); if shape != expected.0 { wrong.push(format!("compat: {label}, imports {path}, {form}")); } - if size_of(&context, "app", &reference, &[]) != expected.1 { + if size_of(&context, "app", reference, &[]) != expected.1 { wrong.push(format!("sizer: {label}, imports {path}, {form}")); } } @@ -211,15 +224,15 @@ fn a_dependencys_bare_name_is_not_the_consumers_declaration() { #[test] fn a_dependencys_qualified_name_is_not_the_consumers_declaration() { assert_eq!( - dependency_shape("s0::A", true), - dependency_shape("s0::A", false) + dependency_shape("package::s0::A", true), + dependency_shape("package::s0::A", false) ); } #[cfg(feature = "deps")] #[test] fn the_sizer_reads_a_dependencys_names_in_its_package() { - for field in ["A", "s0::A"] { + for field in ["A", "package::s0::A"] { let alone = dependency_size(field, false); assert!(alone.is_some(), "`{field}` is sized"); assert_eq!(dependency_size(field, true), alone, "`{field}`"); From 0daf38791beb0cd7832994a116bc20a344d59049 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:35:39 +0800 Subject: [PATCH 3/8] references: clone the path --- core/src/schema/ir/compiler/references.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/schema/ir/compiler/references.rs b/core/src/schema/ir/compiler/references.rs index f092dfb..7982b16 100644 --- a/core/src/schema/ir/compiler/references.rs +++ b/core/src/schema/ir/compiler/references.rs @@ -435,7 +435,7 @@ impl<'p> Scope<'p> { self.bind(Binding { name: alias.clone().unwrap_or(last), kind: Kind::Unknown, - path: parts, + path: parts.clone(), weak: false, span, single: true, From 362b9a9bdab17109eb1022b23fa6750ad22e55c6 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:40:55 +0800 Subject: [PATCH 4/8] references: the tests' helper is not the errors of another module --- core/tests/schema/ir/references.rs | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/core/tests/schema/ir/references.rs b/core/tests/schema/ir/references.rs index 05b5642..af09f4b 100644 --- a/core/tests/schema/ir/references.rs +++ b/core/tests/schema/ir/references.rs @@ -9,7 +9,6 @@ use comline_core::diagnostics::Diagnostic; use comline_core::package::build::PackageSources; use comline_core::package::config::idl::grammar as config_grammar; -use comline_core::package::config::ir::compiler::interpret::interpret_context; use comline_core::package::config::ir::context::ProjectContext; use comline_core::schema::idl::grammar; use comline_core::schema::ir::compiler::references::{ @@ -39,7 +38,7 @@ fn add_schema(project: &mut ProjectContext, namespace: &[&str], source: &str) { } /// What the reference check says of the schema `namespace`. -fn errors(project: &ProjectContext, namespace: &[&str]) -> Vec { +fn reference_errors(project: &ProjectContext, namespace: &[&str]) -> Vec { let namespace: Vec = namespace.iter().map(|s| s.to_string()).collect(); let declarations = project .schema_contexts @@ -62,7 +61,7 @@ fn api_errors(api: &str) -> Vec { let mut project = build_project(); add_schema(&mut project, &["types"], TYPES); add_schema(&mut project, &["api"], api); - errors(&project, &["api"]) + reference_errors(&project, &["api"]) } /// `api` as `api` is after the one fix of the one error it has. @@ -216,7 +215,7 @@ fn a_qualifier_is_a_root_or_a_name_in_scope() { add_schema(&mut project, &["billing", "api"], INVOICE); let skipping = "use package::billing\n\nstruct A {\n i: api::Invoice\n}\n"; add_schema(&mut project, &["app"], skipping); - let errors = errors(&project, &["app"]); + let errors = reference_errors(&project, &["app"]); assert_eq!(errors.len(), 1, "{errors:?}"); assert_eq!(errors[0].code, QUALIFIER_NOT_IN_SCOPE); assert_eq!( @@ -234,7 +233,7 @@ fn a_declaration_and_a_use_of_one_name_is_defined_twice() { let api = "use package::billing::api::Invoice\n\nstruct Invoice {\n data: char[max 64]\n}\n"; add_schema(&mut project, &["api"], api); - let errors = errors(&project, &["api"]); + let errors = reference_errors(&project, &["api"]); assert_eq!(errors.len(), 1, "{errors:?}"); assert_eq!(errors[0].code, DEFINED_TWICE); assert_eq!(errors[0].code.id, "reference::defined-twice"); @@ -262,7 +261,7 @@ fn two_uses_of_one_name_are_defined_twice_and_the_same_use_twice_is_not() { add_schema(&mut project, &["b"], TYPES); let api = "use package::a::User\nuse package::b::User\n\nstruct A {\n id: u64\n}\n"; add_schema(&mut project, &["api"], api); - let errors = errors(&project, &["api"]); + let errors = reference_errors(&project, &["api"]); assert_eq!(errors.len(), 1, "{errors:?}"); assert_eq!(errors[0].code, DEFINED_TWICE); // The later `use` takes the alias. @@ -290,7 +289,7 @@ fn two_uses_of_one_name_are_defined_twice_and_the_same_use_twice_is_not() { } fn errors_of(project: &ProjectContext) -> Vec { - errors(project, &["api"]) + reference_errors(project, &["api"]) } } @@ -302,7 +301,7 @@ fn every_error_is_reported_not_the_first() { add_schema(&mut project, &["types"], TYPES); let api = "use package::types\n\nstruct User {\n id: u8\n}\n\nstruct A {\n first: Order\n second: nope::User\n third: types::Order\n}\n"; add_schema(&mut project, &["api"], api); - let errors = errors(&project, &["api"]); + let errors = reference_errors(&project, &["api"]); let codes: Vec<&str> = errors.iter().map(|e| e.code.id).collect(); assert_eq!( codes, @@ -341,7 +340,7 @@ fn a_use_that_fails_to_resolve_still_brings_its_name_in() { &["api"], "use modles::User\n\nstruct A {\n u: User\n}\n", ); - assert!(errors(&project, &["api"]).is_empty()); + assert!(reference_errors(&project, &["api"]).is_empty()); let error = compile(&[ (&["models"], TYPES), (&["api"], "use modles::User\n\nstruct A {\n u: User\n}\n"), From 5132a74b20da28fbe0ecf673893f133f0369ba57 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:44:33 +0800 Subject: [PATCH 5/8] references: any is no name; the tests that wrote a qualified name after an item use --- core/src/schema/ir/compiler/references.rs | 31 +++++++++++------------ core/tests/package/from_sources.rs | 7 ++--- core/tests/schema/ir/imports.rs | 5 +++- core/tests/schema/ir/references.rs | 4 +-- 4 files changed, 25 insertions(+), 22 deletions(-) diff --git a/core/src/schema/ir/compiler/references.rs b/core/src/schema/ir/compiler/references.rs index 7982b16..fff1ccd 100644 --- a/core/src/schema/ir/compiler/references.rs +++ b/core/src/schema/ir/compiler/references.rs @@ -73,13 +73,14 @@ pub struct Written { } /// Every type name written in `declarations`, in source order, as it is -/// written (`User`, `types::User`). Primitives, and a validator's `any`, are -/// not names. +/// written (`User`, `types::User`). Primitives, and `any`, are not names: +/// `any` is a keyword in a validator's `for`, and validation says where else +/// it may not stand. pub fn named_types(declarations: &[rust_sitter::Spanned]) -> Vec { let mut out = vec![]; for decl in declarations { match &decl.value { - Declaration::Const(c) => names_in(c.type_def(), c.type_def_span(), false, &mut out), + Declaration::Const(c) => names_in(c.type_def(), c.type_def_span(), &mut out), Declaration::Struct(s) => { for field in s.fields() { names_in( @@ -105,10 +106,10 @@ pub fn named_types(declarations: &[rust_sitter::Spanned]) -> Vec]) -> Vec { - names_in(a.target_type(), a.target_type_span(), false, &mut out) - } + Declaration::TypeAlias(a) => names_in(a.target_type(), a.target_type_span(), &mut out), Declaration::Validator(v) => { if let Some(targets) = &v.targets { - names_in(&targets.first.value, targets.first.span, true, &mut out); + names_in(&targets.first.value, targets.first.span, &mut out); for rest in &targets.rest { - names_in(&rest.target.value, rest.target.span, true, &mut out); + names_in(&rest.target.value, rest.target.span, &mut out); } } for property in v.properties() { let ty = &property.value.property_type; - names_in(&ty.value, ty.span, false, &mut out); + names_in(&ty.value, ty.span, &mut out); } } _ => {} @@ -143,20 +142,20 @@ pub fn named_types(declarations: &[rust_sitter::Spanned]) -> Vec) { +/// validator's `for` (core#290 leaves where it may stand to validation). +fn names_in(ty: &Type, within: (usize, usize), out: &mut Vec) { match ty { Type::Named(id) => { let name = id.text.clone(); - if PrimitiveType::from_name(&name).is_some() || (any_is_keyword && name == "any") { + if PrimitiveType::from_name(&name).is_some() || name == "any" { return; } out.push(Written { name, within }); } - Type::Array(array) => names_in(array.elem_type(), within, any_is_keyword, out), + Type::Array(array) => names_in(array.elem_type(), within, out), Type::Union(union) => { for member in union.members() { - names_in(member, within, any_is_keyword, out); + names_in(member, within, out); } } _ => {} diff --git a/core/tests/package/from_sources.rs b/core/tests/package/from_sources.rs index a54a105..6f53d1a 100644 --- a/core/tests/package/from_sources.rs +++ b/core/tests/package/from_sources.rs @@ -52,11 +52,12 @@ fn multiple_schemas_are_all_interpreted() { #[test] fn cross_schema_use_resolves_across_the_added_schemas() { - // The bare name (`use ns::Name` -> `Name`), the qualified form (`ns::Name`), - // and an alias (`use ns::Name as X` -> `X`) all resolve. + // The bare name (`use ns::Name` -> `Name`), the qualified form (`ns::Name` + // after `use ns`, which brings in `ns`; core#290), and an alias + // (`use ns::Name as X` -> `X`) all resolve. let cases = [ ("use package::types::User", "User"), - ("use package::types::User", "types::User"), + ("use package::types", "types::User"), ("use package::types::User as Account", "Account"), ]; for (import, reference) in cases { diff --git a/core/tests/schema/ir/imports.rs b/core/tests/schema/ir/imports.rs index 98c6566..25004c1 100644 --- a/core/tests/schema/ir/imports.rs +++ b/core/tests/schema/ir/imports.rs @@ -967,5 +967,8 @@ fn test_a_path_that_matches_nothing_is_unresolved_not_a_bare_own_path() { let errors = bare_path_errors(&project, &["api"]); assert_eq!(errors.len(), 1, "{errors:?}"); assert_eq!(errors[0].code.id, "import::unresolved"); - assert!(errors[0].fix.is_none()); + // Its fix is the typo's (core#286), not the bare path's: it writes the + // schema it was close to, with `package::`. + let fix = errors[0].fix.as_ref().expect("the typo's fix"); + assert_eq!(fix.title, "Write `package::types::User`"); } diff --git a/core/tests/schema/ir/references.rs b/core/tests/schema/ir/references.rs index af09f4b..4ea085a 100644 --- a/core/tests/schema/ir/references.rs +++ b/core/tests/schema/ir/references.rs @@ -409,8 +409,8 @@ fn what_is_written_the_same_gives_the_same_frozen_schema_whichever_the_spelling( field_of_a(&project, "app").to_string() }; assert_eq!( - frozen("use package::billing::api\n\nstruct A {\n i: api::Invoice[]\n}\n"), - frozen("struct A {\n i: package::billing::api::Invoice[]\n}\n"), + frozen("use package::billing::api\n\nstruct A {\n i: api::Invoice[max 4]\n}\n"), + frozen("struct A {\n i: package::billing::api::Invoice[max 4]\n}\n"), ); } From c0ce41a00db7dcc149a1e8e3b1c9b15ef0f7ff69 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 10:46:55 +0800 Subject: [PATCH 6/8] references: names_in takes no flag --- core/src/schema/ir/compiler/references.rs | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/core/src/schema/ir/compiler/references.rs b/core/src/schema/ir/compiler/references.rs index fff1ccd..fde11ff 100644 --- a/core/src/schema/ir/compiler/references.rs +++ b/core/src/schema/ir/compiler/references.rs @@ -86,7 +86,6 @@ pub fn named_types(declarations: &[rust_sitter::Spanned]) -> Vec]) -> Vec]) -> Vec Date: Mon, 16 Nov 2026 10:52:14 +0800 Subject: [PATCH 7/8] references: a test that each spelling reaches billing's Invoice and not the decoy --- core/tests/schema/ir/references.rs | 70 ++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) diff --git a/core/tests/schema/ir/references.rs b/core/tests/schema/ir/references.rs index 4ea085a..c796df2 100644 --- a/core/tests/schema/ir/references.rs +++ b/core/tests/schema/ir/references.rs @@ -493,3 +493,73 @@ fn a_whole_namespace_use_and_a_qualified_name_freeze_as_they_always_did() { // what it was, whatever the file may now write. assert_eq!(imports, ["types", "types::User", "types::Order"]); } + +// ---- A qualified reference reaches the declaration it resolves to. + +/// The specification's `references/resolved-*` cases put an `Invoice` that holds +/// an unbounded string in `archive` beside the bounded one in `billing::api`, +/// to tell which a name reached by what it freezes as. Core holds a type no +/// protocol reaches to be bounded (core#98), so there the one in `archive` +/// is marked: a protocol of its own, `@unverified`. +#[test] +fn each_spelling_reaches_billing_and_not_the_decoy_in_archive() { + let config = "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n"; + let archive = "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n"; + let build = |use_line: &str, reference: &str| { + let api = + format!("{use_line}\n\nprotocol Orders {{\n function send(i: {reference});\n}}\n"); + PackageSources::new() + .config(config) + .schema(["archive"], archive) + .schema(["billing", "api"], INVOICE) + .schema(["api"], api) + .compile() + .map_err(|e| e.to_string()) + }; + + let to_billing = [ + ("use package::billing::api::Invoice", "Invoice"), + ("use package::billing::api", "api::Invoice"), + ("use package::billing", "billing::api::Invoice"), + ("use package::billing::api as b", "b::Invoice"), + ("", "package::billing::api::Invoice"), + ]; + for (use_line, reference) in to_billing { + let project = + build(use_line, reference).unwrap_or_else(|e| panic!("{use_line} / {reference}: {e}")); + let schema = project + .schema_contexts + .iter() + .find(|s| s.borrow().namespace_joined() == "api") + .unwrap(); + let frozen = schema.borrow().frozen_schema.borrow().clone().unwrap(); + let given_up = frozen.iter().find_map(|u| match u { + FrozenUnit::Protocol { + name, parameters, .. + } if name == "Orders" => { + Some(comline_core::schema::ir::unverified::frozen_set(parameters).to_vec()) + } + _ => None, + }); + assert_eq!( + given_up, + Some(vec![]), + "{use_line} / {reference}: reached the bounded Invoice" + ); + } + + // The same, reaching the decoy: Orders is not marked, and `archive`'s + // Invoice holds an unbounded string. + for (use_line, reference) in [ + ("use package::archive", "archive::Invoice"), + ("", "package::archive::Invoice"), + ] { + let error = build(use_line, reference) + .err() + .unwrap_or_else(|| panic!("{use_line} / {reference}: built")); + assert!( + error.contains("bounds::unbounded"), + "{use_line} / {reference}: {error}" + ); + } +} From 41326bc4ebaeec861ccbaa3d0001890ce465d830 Mon Sep 17 00:00:00 2001 From: Kinflou Date: Mon, 16 Nov 2026 11:15:05 +0800 Subject: [PATCH 8/8] Pin the specification at 8a9d47d (specification#18, the decoy is reached by a marked protocol and the bounded/unreached cases) Drops each_spelling_reaches_billing_and_not_the_decoy_in_archive: the references/resolved-* cases hold the same five spellings now. --- core/Cargo.toml | 2 +- core/tests/schema/ir/references.rs | 70 --------------- core/tests/spec/REV | 2 +- core/tests/spec/cases/bounded.json | 104 +++++++++++++++++++++ core/tests/spec/cases/references.json | 124 ++++++++++++++++++++++---- 5 files changed, 213 insertions(+), 89 deletions(-) diff --git a/core/Cargo.toml b/core/Cargo.toml index 0dc4373..f4f3e83 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -27,7 +27,7 @@ comline-ir-formats = { path = "formats" } # The specification's catalog of shared names: guarantees, facts and their # values, the official encodings' aliases and frozen spellings. no_std and # dependency-free, so the IR-only build has it too. -comline-catalog = { git = "https://github.com/ComlineProject/specification", rev = "0b376dd6b6e3c1ee64b46c88b29b988b47d01d39" } +comline-catalog = { git = "https://github.com/ComlineProject/specification", rev = "8a9d47dca94e34521bae37d664d032dd3654384b" } # General eyre = "0.6.8" diff --git a/core/tests/schema/ir/references.rs b/core/tests/schema/ir/references.rs index c796df2..4ea085a 100644 --- a/core/tests/schema/ir/references.rs +++ b/core/tests/schema/ir/references.rs @@ -493,73 +493,3 @@ fn a_whole_namespace_use_and_a_qualified_name_freeze_as_they_always_did() { // what it was, whatever the file may now write. assert_eq!(imports, ["types", "types::User", "types::Order"]); } - -// ---- A qualified reference reaches the declaration it resolves to. - -/// The specification's `references/resolved-*` cases put an `Invoice` that holds -/// an unbounded string in `archive` beside the bounded one in `billing::api`, -/// to tell which a name reached by what it freezes as. Core holds a type no -/// protocol reaches to be bounded (core#98), so there the one in `archive` -/// is marked: a protocol of its own, `@unverified`. -#[test] -fn each_spelling_reaches_billing_and_not_the_decoy_in_archive() { - let config = "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n"; - let archive = "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n"; - let build = |use_line: &str, reference: &str| { - let api = - format!("{use_line}\n\nprotocol Orders {{\n function send(i: {reference});\n}}\n"); - PackageSources::new() - .config(config) - .schema(["archive"], archive) - .schema(["billing", "api"], INVOICE) - .schema(["api"], api) - .compile() - .map_err(|e| e.to_string()) - }; - - let to_billing = [ - ("use package::billing::api::Invoice", "Invoice"), - ("use package::billing::api", "api::Invoice"), - ("use package::billing", "billing::api::Invoice"), - ("use package::billing::api as b", "b::Invoice"), - ("", "package::billing::api::Invoice"), - ]; - for (use_line, reference) in to_billing { - let project = - build(use_line, reference).unwrap_or_else(|e| panic!("{use_line} / {reference}: {e}")); - let schema = project - .schema_contexts - .iter() - .find(|s| s.borrow().namespace_joined() == "api") - .unwrap(); - let frozen = schema.borrow().frozen_schema.borrow().clone().unwrap(); - let given_up = frozen.iter().find_map(|u| match u { - FrozenUnit::Protocol { - name, parameters, .. - } if name == "Orders" => { - Some(comline_core::schema::ir::unverified::frozen_set(parameters).to_vec()) - } - _ => None, - }); - assert_eq!( - given_up, - Some(vec![]), - "{use_line} / {reference}: reached the bounded Invoice" - ); - } - - // The same, reaching the decoy: Orders is not marked, and `archive`'s - // Invoice holds an unbounded string. - for (use_line, reference) in [ - ("use package::archive", "archive::Invoice"), - ("", "package::archive::Invoice"), - ] { - let error = build(use_line, reference) - .err() - .unwrap_or_else(|| panic!("{use_line} / {reference}: built")); - assert!( - error.contains("bounds::unbounded"), - "{use_line} / {reference}: {error}" - ); - } -} diff --git a/core/tests/spec/REV b/core/tests/spec/REV index 816a162..acd4e53 100644 --- a/core/tests/spec/REV +++ b/core/tests/spec/REV @@ -1 +1 @@ -0b376dd6b6e3c1ee64b46c88b29b988b47d01d39 +8a9d47dca94e34521bae37d664d032dd3654384b diff --git a/core/tests/spec/cases/bounded.json b/core/tests/spec/cases/bounded.json index b417922..86a8f45 100644 --- a/core/tests/spec/cases/bounded.json +++ b/core/tests/spec/cases/bounded.json @@ -371,6 +371,110 @@ "builds": true, "diagnostics": [] } + }, + { + "id": "bounded/unreached-unmarked", + "description": "a struct no protocol reaches, with a string without a maximum, is an error: it is a type another package can use", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-list-unmarked", + "description": "a struct no protocol reaches, with a list without a maximum, is an error too", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: u8[]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-allowed-still-unmarked", + "description": "allowing @unverified in the package doesn't cover a type no protocol reaches: nothing marked it", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: string\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "builds": false, + "diagnostics": [ + { + "code": "bounds::unbounded", + "severity": "error" + } + ] + } + }, + { + "id": "bounded/unreached-bounded", + "description": "a struct no protocol reaches, bounded, gives nothing up and builds", + "packages": [ + { + "name": "app", + "config": "congregation app\nspecification_version = 1\n", + "schemas": [ + { + "path": "src/models.ids", + "text": "struct Blob {\n data: char[max 64]\n tags: u8[max 16]\n}\n" + } + ], + "dependencies": [] + } + ], + "build": "app", + "expect": { + "protocols": [], + "builds": true, + "diagnostics": [] + } } ] } diff --git a/core/tests/spec/cases/references.json b/core/tests/spec/cases/references.json index 8f7675e..8e7a4f4 100644 --- a/core/tests/spec/cases/references.json +++ b/core/tests/spec/cases/references.json @@ -907,11 +907,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids", @@ -928,13 +928,31 @@ "build": "app", "expect": { "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, { "name": "Orders", "given_up": [] } ], "builds": true, - "diagnostics": [] + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] } }, { @@ -943,11 +961,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids", @@ -964,13 +982,31 @@ "build": "app", "expect": { "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, { "name": "Orders", "given_up": [] } ], "builds": true, - "diagnostics": [] + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] } }, { @@ -979,11 +1015,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids", @@ -1000,13 +1036,31 @@ "build": "app", "expect": { "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, { "name": "Orders", "given_up": [] } ], "builds": true, - "diagnostics": [] + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] } }, { @@ -1015,11 +1069,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids", @@ -1036,13 +1090,31 @@ "build": "app", "expect": { "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, { "name": "Orders", "given_up": [] } ], "builds": true, - "diagnostics": [] + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] } }, { @@ -1051,11 +1123,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids", @@ -1072,13 +1144,31 @@ "build": "app", "expect": { "protocols": [ + { + "name": "Dump", + "given_up": [ + "bounded_size" + ], + "acknowledged": [ + { + "guarantee": "bounded_size", + "scope": "protocol", + "reason": "the archive keeps what it is given" + } + ] + }, { "name": "Orders", "given_up": [] } ], "builds": true, - "diagnostics": [] + "diagnostics": [ + { + "code": "unverified::bounded-size", + "severity": "warning" + } + ] } }, { @@ -1087,11 +1177,11 @@ "packages": [ { "name": "app", - "config": "congregation app\nspecification_version = 1\n", + "config": "congregation app\nspecification_version = 1\nsettings = { annotations = { unverified = { allowed = true } } }\n", "schemas": [ { "path": "src/archive.ids", - "text": "struct Invoice {\n data: string\n}\n" + "text": "struct Invoice {\n data: string\n}\n\n@unverified = \"the archive keeps what it is given\"\nprotocol Dump {\n function put(i: Invoice);\n}\n" }, { "path": "src/billing/api.ids",