diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d8b2cbce565..0ef49c3e082 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -152,7 +152,8 @@ See [Mergify priorities](https://docs.mergify.com/merge-queue/priority/) and [Mergify stacks](https://docs.mergify.com/merge-queue/stacks/) (`stack/*` heads pushed by `mergify stack push --no-github-native`) use the `changes` queue. A member above the bottom targets the branch below it and carries a -`Depends-On: #N` marker; the queue accepts it on that basis and lands the whole +`Depends-On: #N` or same-repository `Depends-On: https://github.com/OWNER/REPO/pull/N` +marker; the queue accepts it on that basis and lands the whole chain on the stack root, bottom-up. Queueing the top member queues every member below it. The batch validator resolves each member's root through the same marker chain, so a stack branch without it is still refused. diff --git a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs index 115e10a14b3..3f6ee374de7 100644 --- a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs +++ b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs @@ -225,12 +225,12 @@ fn collect_dims(module: &Module, var_id: VarId) -> Result, ParserErro "array", &mut dims, )?; - // For enum-typed variables, the width Shape is empty but the actual - // bit width is encoded in the TypeKind. Use kind.width() as the - // base scalar width when the explicit width shape is absent. + // Enums and aggregates encode their packed width in TypeKind rather + // than the width Shape. Even a one-bit struct/union needs that dimension: + // Veryl represents member access as a select into the packed aggregate. if width.is_empty() { if let Some(kind_width) = var_type.kind.width() - && kind_width > 1 + && (kind_width > 1 || (kind_width == 1 && var_type.is_struct_union())) { dims.push(kind_width); } diff --git a/crates/celox-test-suite/src/veryl/cases/struct_constructor.vtest b/crates/celox-test-suite/src/veryl/cases/struct_constructor.vtest index 1ff32fbb1b2..34ceec524bd 100644 --- a/crates/celox-test-suite/src/veryl/cases/struct_constructor.vtest +++ b/crates/celox-test-suite/src/veryl/cases/struct_constructor.vtest @@ -53,3 +53,63 @@ o_cut = Cut'{y: wide}; (assert_eq o_pad 0x0B) ; wide(8bit) -> member logic<4> should keep lower 4 bits. (assert_eq o_cut 0xB)) + +(case test_single_bit_aggregate_members + (source "test.veryl" #" +module Top ( + i: input logic, + rst: input reset_sync_low, + members: output logic<3>, + reset_member: output logic, +) { + struct Single { value: logic, } + struct Nested { inner: Single, } + struct Reset { value: reset_sync_low, } + union Overlay { value: logic, other: logic, } + var single: Single; + var nested: Nested; + var reset_pair: Reset; + var overlay: Overlay; + assign single.value = i; + assign nested.inner.value = i; + assign reset_pair.value = rst; + assign overlay.value = i; + assign members = {single.value, nested.inner.value, overlay.other}; + assign reset_member = reset_pair.value; +} +"#) + (top Top) + (modify (set i 0) (set rst 1)) + (assert_eq members 0) + (assert_eq reset_member 1) + (modify (set i 1) (set rst 0)) + (assert_eq members 7) + (assert_eq reset_member 0)) + +(case test_single_bit_struct_ff + (source "test.veryl" #" +module Top ( + clk: input clock, + rst: input reset, + i: input logic, + o: output logic, +) { + struct Single { value: logic, } + var registered: Single; + always_ff (clk, rst) { + if_reset { registered.value = 1'b0; } + else { registered.value = i; } + } + assign o = registered.value; +} +"#) + (top Top) + (modify (set rst 0) (set i 1)) + (tick clk) + (assert_eq o 0) + (modify (set rst 1)) + (tick clk) + (assert_eq o 1) + (modify (set i 0)) + (tick clk) + (assert_eq o 0)) diff --git a/crates/celox/tests/struct_constructor.rs b/crates/celox/tests/struct_constructor.rs index 359538e8a76..a547523e541 100644 --- a/crates/celox/tests/struct_constructor.rs +++ b/crates/celox/tests/struct_constructor.rs @@ -3,6 +3,13 @@ mod test_utils; all_backends! { + fn test_single_bit_aggregate_members(sim) { + @case "struct_constructor::test_single_bit_aggregate_members"; + } + + fn test_single_bit_struct_ff(sim) { + @case "struct_constructor::test_single_bit_struct_ff"; + } fn test_struct_constructor_comb_assignment(sim) { @case "struct_constructor::test_struct_constructor_comb_assignment"; diff --git a/flake.lock b/flake.lock index 60c6320088b..df9a372e0e9 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792195366, - "narHash": "sha256-kqOyKz1zB7CB60DYPWx3fwFnL0R58A6Zzdmgiv15o7Y=", + "lastModified": 1792488653, + "narHash": "sha256-6mDIj7DP6kHQAdT0B7N8QpC3KBrY6W8LEenKg3GGfM0=", "owner": "tignear", "repo": "nix-packages", - "rev": "433f006183bab18dfcaa0a3104ec1c7c9bc907af", + "rev": "683234e1ef474a6fbb653ce7ec11aa4657d49975", "type": "github" }, "original": { diff --git a/packages/playground/package.json b/packages/playground/package.json index 3f8035c9154..74f2cbca4d3 100644 --- a/packages/playground/package.json +++ b/packages/playground/package.json @@ -9,7 +9,7 @@ "preview": "vite preview", "test": "vitest run", "typecheck": "node test/generate-sidecars.mjs && tsc -p .", - "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && vitest run --config test/fixtures/injected-components/vitest.config.ts && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", + "test:vite-components": "vitest run test/vite-plugin-cache.test.ts test/generated-dts.test.ts test/vite-assertion-bytes.test.ts test/vite-plugin-cache-real.test.ts test/vite-plugin-watch.test.ts test/sidecar-orphans.test.ts test/sidecar-lock.test.ts && node test/fixtures/injected-components/cache-e2e.mjs && node test/fixtures/injected-components/dependency-e2e.mjs && node test/fixtures/source-watch/watch-e2e.mjs && node test/fixtures/source-watch/build-watch-e2e.mjs && node test/fixtures/source-watch/component-watch-e2e.mjs", "test:lsp-components": "pnpm run test:vite-components && node test/fixtures/injected-components/lsp-e2e.mjs", "test:e2e": "pnpm run build && playwright test", "test:watch": "vitest", diff --git a/packages/playground/test/fixtures/injected-components/cache-e2e.mjs b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs new file mode 100644 index 00000000000..e842763f1a8 --- /dev/null +++ b/packages/playground/test/fixtures/injected-components/cache-e2e.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const vitest = join( + dirname(fileURLToPath(import.meta.resolve("vitest/package.json"))), + "vitest.mjs", +); +for (const layout of ["internal", "external"]) { + const cache = mkdtempSync(join(tmpdir(), "celox-vitest-cache-")); + const client = + layout === "external" + ? mkdtempSync(join(import.meta.dirname, ".cache-client-")) + : undefined; + try { + for (const phase of ["cold", "warm"]) { + const result = spawnSync( + process.execPath, + [ + vitest, + "run", + "--config", + join(import.meta.dirname, "vitest.config.ts"), + "--fsModuleCachePath", + cache, + ], + { + cwd: import.meta.dirname, + env: { ...process.env, CELOX_TEST_EXTERNAL_VITE_ROOT: client ?? "" }, + encoding: "utf8", + timeout: 120_000, + }, + ); + process.stdout.write(result.stdout ?? ""); + process.stderr.write(result.stderr ?? ""); + assert.ifError(result.error); + assert.equal( + result.status, + 0, + `${layout} ${phase} module-cache run failed`, + ); + } + } finally { + rmSync(cache, { recursive: true, force: true }); + if (client) rmSync(client, { recursive: true, force: true }); + } +} diff --git a/packages/playground/test/fixtures/injected-components/vitest.config.ts b/packages/playground/test/fixtures/injected-components/vitest.config.ts index bc89ddd9b39..136b179cd1f 100644 --- a/packages/playground/test/fixtures/injected-components/vitest.config.ts +++ b/packages/playground/test/fixtures/injected-components/vitest.config.ts @@ -14,7 +14,7 @@ const virtualTbStep: Plugin = { }; export default defineConfig({ - root: import.meta.dirname, + root: process.env.CELOX_TEST_EXTERNAL_VITE_ROOT || import.meta.dirname, resolve: { alias: { "@fixture/tb-helper": resolve( @@ -26,8 +26,9 @@ export default defineConfig({ plugins: [ virtualTbStep, celox({ + projectRoot: import.meta.dirname, testbenchComponents: "./tb-components.ts", }), ], - test: { include: ["entry.test.ts"] }, + test: { include: [resolve(import.meta.dirname, "entry.test.ts")] }, }); diff --git a/packages/playground/test/vite-plugin-watch.test.ts b/packages/playground/test/vite-plugin-watch.test.ts index e7763c6de41..642f863615c 100644 --- a/packages/playground/test/vite-plugin-watch.test.ts +++ b/packages/playground/test/vite-plugin-watch.test.ts @@ -1,5 +1,11 @@ import { EventEmitter } from "node:events"; -import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { + mkdirSync, + mkdtempSync, + rmSync, + utimesSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { normalizePath } from "vite"; @@ -1045,3 +1051,143 @@ test.each([true, false])( expect(watcher.add).not.toHaveBeenCalled(); }, ); + +// Vitest's persistent module cache replays imports as URLs rooted at Vite's +// root, rather than their original paths relative to the importer. +test("cached root-relative imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-cached-import-")); + roots.push(root); + mkdirSync(join(root, "src")); + writeFileSync(join(root, "src", "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const { plugin, context } = await initialize(root); + for (const [url, file] of [ + ["/src/Main.veryl", join(root, "src", "Main.veryl")], + [ + "/src/Main.veryl?dse=preserveAllPorts", + `${join(root, "src", "Main.veryl")}?dse=preserveAllPorts`, + ], + ["/Veryl.toml?celox-project", `${join(root, "Veryl.toml")}?celox-project`], + [ + "/src/Main.veryl?celox-watch", + `${join(root, "src", "Main.veryl")}?celox-watch`, + ], + ]) { + const id = (plugin.resolveId as Function)(url, join(root, "index.html")); + expect(id).toBe(normalizePath(file!)); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + expect((plugin.resolveId as Function)("/missing.veryl")).toBeUndefined(); +}); + +// A project outside Vite's root is replayed through the /@fs/ URL namespace. +test("cached external project imports retain their generated module identity", async () => { + const root = mkdtempSync(join(tmpdir(), "celox-external-cache-")); + const client = mkdtempSync(join(tmpdir(), "celox-external-client-")); + roots.push(root, client); + writeFileSync(join(root, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(root, "Veryl.toml"), "[project]\nname = 'test'\n"); + const plugin = celox({ projectRoot: root }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + const file = normalizePath(join(root, "Main.veryl")) + query; + const id = (plugin.resolveId as Function)( + `/@fs/${file.replace(/^\//, "")}`, + join(client, "index.html"), + ); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + const project = `${normalizePath(join(root, "Veryl.toml"))}?celox-project`; + const id = (plugin.resolveId as Function)( + `/@fs/${project.replace(/^\//, "")}`, + ); + expect(id).toBe(project); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); +}); + +// Both the host-absolute and Vite-root-relative paths exist. Their existence +// alone must not let an unrelated host file take over a cached project URL. +test("cached URLs prefer the project over colliding host paths", async () => { + const client = mkdtempSync(join(tmpdir(), "celox-collision-client-")); + const host = mkdtempSync(join(tmpdir(), "celox-collision-host-")); + roots.push(client, host); + const urlRoot = normalizePath(host).replace(/^[A-Z]:/i, ""); + const project = join(client, urlRoot.replace(/^\//, "")); + mkdirSync(project, { recursive: true }); + for (const dir of [host, project]) { + writeFileSync(join(dir, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(dir, "Veryl.toml"), "[project]\nname = 'test'\n"); + } + const plugin = celox({ projectRoot: project }); + const context = { addWatchFile: vi.fn(), warn: vi.fn() }; + await (plugin.configResolved as Function)({ root: client }); + await (plugin.buildStart as Function).call(context); + for (const [name, query] of [ + ["Main.veryl", ""], + ["Main.veryl", "?dse=preserveAllPorts"], + ["Main.veryl", "?celox-watch"], + ["Veryl.toml", "?celox-project"], + ]) { + const file = normalizePath(join(project, name!)) + query; + const url = `${urlRoot}/${name}${query}`; + const id = (plugin.resolveId as Function)(url, join(client, "index.html")); + expect(id).toBe(file); + expect((plugin.load as Function).call(context, id)).toBeTypeOf("string"); + } + + // Canonical absolute project IDs must stay stable even if their root-relative + // lookalikes also exist. Explicit /@fs/ URLs retain their absolute meaning. + const mirror = join( + client, + normalizePath(project) + .replace(/^[A-Z]:/i, "") + .replace(/^\//, ""), + ); + mkdirSync(mirror, { recursive: true }); + writeFileSync(join(mirror, "Main.veryl"), "module Main {}\n"); + writeFileSync(join(mirror, "Veryl.toml"), "[project]\nname = 'other'\n"); + for (const name of ["Main.veryl", "Veryl.toml?celox-project"]) { + const file = normalizePath(join(project, name)); + expect((plugin.resolveId as Function)(file)).toBe(file); + } + const hostFile = normalizePath(join(host, "Main.veryl")); + expect( + (plugin.resolveId as Function)(`/@fs/${hostFile.replace(/^\//, "")}`), + ).toBe(hostFile); +}); + +test.each([false, true])( + "cached prefix-shaped URLs fall back to the Vite root (filesystem root=%s)", + async (filesystemRoot) => { + const project = mkdtempSync(join(tmpdir(), "celox-prefix-project-")); + roots.push(project); + const client = join(project, "client"); + const url = filesystemRoot + ? `/celox-prefix-${project.split(/[\\/]/).at(-1)}/Main.veryl` + : normalizePath(join(project, "Main.veryl")).replace(/^[A-Z]:/i, ""); + const rooted = join(client, url.replace(/^[A-Z]:/i, "").replace(/^\//, "")); + mkdirSync(dirname(rooted), { recursive: true }); + writeFileSync(rooted, "module Main {}\n"); + const plugin = celox({ projectRoot: filesystemRoot ? "/" : project }); + // Resolution does not need buildStart; do not generate sidecars at '/'. + await (plugin.configResolved as Function)({ root: client }); + for (const query of ["", "?dse=preserveAllPorts", "?celox-watch"]) { + expect((plugin.resolveId as Function)(url + query)).toBe( + normalizePath(rooted) + query, + ); + } + expect( + (plugin.resolveId as Function)(`/@fs/${url.replace(/^\//, "")}`), + ).toBeUndefined(); + if (!filesystemRoot) { + // Once the canonical project file exists, keep that identity even though + // the cached-root lookalike exists too. + writeFileSync(join(project, "Main.veryl"), "module Main {}\n"); + const canonical = normalizePath(join(project, "Main.veryl")); + expect((plugin.resolveId as Function)(canonical)).toBe(canonical); + } + }, +); diff --git a/packages/vite-plugin/src/index.ts b/packages/vite-plugin/src/index.ts index ad26a777148..793e66b885c 100644 --- a/packages/vite-plugin/src/index.ts +++ b/packages/vite-plugin/src/index.ts @@ -411,16 +411,29 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { // Split off query string (e.g. "?dse=preserveAllPorts") const [rawPath, queryStr] = source.split("?", 2); if (source.startsWith("\0")) return; - if (queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY) { - const id = normalizePath(source); - resolvedIds.add(id); - return id; - } - if (!rawPath!.endsWith(".veryl")) return; + const generatedQuery = + queryStr === PROJECT_QUERY || queryStr === WATCH_QUERY; + if (!generatedQuery && !rawPath!.endsWith(".veryl")) return; // Resolve to absolute path let absPath: string; - if (isAbsolute(rawPath!)) { + if (rawPath!.startsWith("/@fs/")) { + // Vite uses /@fs/ for files outside its root. Keep POSIX roots + // and Windows drive letters when decoding that URL namespace. + const file = normalizePath(rawPath!.slice("/@fs/".length)); + absPath = + file.startsWith("/") || /^[A-Z]:/i.test(file) ? file : `/${file}`; + } else if ( + rawPath!.startsWith("/") && + (!normalizePath(rawPath!).startsWith(projectPrefix) || + !existsSync(rawPath!)) + ) { + // Keep existing canonical project files, but a matching prefix alone + // does not make a cached URL absolute. Root other URLs at Vite's + // root even when an unrelated host file exists. + const rooted = resolve(viteConfig.root, `.${rawPath}`); + absPath = existsSync(rooted) ? rooted : rawPath!; + } else if (isAbsolute(rawPath!)) { absPath = rawPath!; } else if (importer) { absPath = resolve(dirname(importer.split("?", 1)[0]!), rawPath!); @@ -430,8 +443,8 @@ export default function celoxPlugin(options?: CeloxPluginOptions): Plugin { absPath = normalizePath(absPath); - // Only handle .veryl files that exist - if (!existsSync(absPath)) return; + // Generated watch modules may refer to optional configuration files. + if (!generatedQuery && !existsSync(absPath)) return; // Preserve the real file identity so Vite/Vitest can trace changes. const id = absPath + (queryStr ? `?${queryStr}` : ""); diff --git a/scripts/check-mergify-batch.mjs b/scripts/check-mergify-batch.mjs index 3cff129ee86..0bea49aafeb 100644 --- a/scripts/check-mergify-batch.mjs +++ b/scripts/check-mergify-batch.mjs @@ -26,12 +26,24 @@ export function batchPullRequestNumbers(metadata) { // Mergify's queue lands stack members on the stack root, while each member // targets the head branch of the member below it. Resolve that root through // the `Depends-On:` chain, matching the queue's own stack recognition. +export function stackDependency(repository, body) { + const marker = + /^Depends-On: (?:#([1-9]\d*)|https:\/\/github\.com\/([^/\s]+\/[^/\s]+)\/pull\/([1-9]\d*))\s*$/m.exec(body ?? ""); + if ( + !marker || + (marker[2] && marker[2].toLowerCase() !== repository.toLowerCase()) + ) + return null; + const number = Number(marker[1] ?? marker[3]); + return Number.isSafeInteger(number) ? number : null; +} + export async function stackRootRef(repository, pull, api = githubJson) { for (let depth = 0; depth < 20; depth++) { const ref = pull.base?.ref; - const below = /^Depends-On: #(\d+)\s*$/m.exec(pull.body ?? ""); + const below = stackDependency(repository, pull.body); if (!ref?.startsWith("stack/") || !below) return ref; - pull = await api(`/repos/${repository}/pulls/${below[1]}`); + pull = await api(`/repos/${repository}/pulls/${below}`); if (pull.head?.ref !== ref || pull.head?.repo?.full_name !== repository) return ref; } diff --git a/scripts/check-mergify-batch.test.mjs b/scripts/check-mergify-batch.test.mjs index ea937633bc0..bd0f701f5c6 100644 --- a/scripts/check-mergify-batch.test.mjs +++ b/scripts/check-mergify-batch.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import { batchPullRequestNumbers, + stackDependency, validateBatch, } from "./check-mergify-batch.mjs"; @@ -103,37 +104,58 @@ test("rejects source PRs with invalid titles or another target branch", async () } }); -test("stack members are validated against the stack root", async () => { - const f = fixture(); - const top = { - ...f.source, - head: { - sha: sourceSha, - ref: "stack/u/feat/b--2", - repo: { full_name: "o/r" }, - }, - base: { ref: "stack/u/feat/a--1" }, - body: "Adds b.\n\nDepends-On: #12\n", - }; - const bottom = { - ...f.source, - head: { - sha: sourceSha, - ref: "stack/u/feat/a--1", - repo: { full_name: "o/r" }, - }, - }; - const api = async (path) => { - if (path === "/repos/o/r/pulls/12") return bottom; - if (path === "/repos/o/r/pulls/13") return top; - return f.api(path); - }; - assert.deepEqual( - await validateBatch(f.input, api, f.commits, f.policy), - [12, 13], - ); +test("stack dependencies accept local shorthand and same-repository GitHub URLs", () => { + for (const body of [ + "Depends-On: #12", + "Text\n\nDepends-On: https://github.com/o/r/pull/12\r\n", + "Depends-On: https://github.com/O/R/pull/12", + ]) + assert.equal(stackDependency("o/r", body), 12); + for (const body of [ + undefined, + "Depends-On: #0", + "Depends-On: #9007199254740992", + "Depends-On: https://github.com/other/r/pull/12", + "Depends-On: https://github.com/o/r/pull/12/extra", + "Depends-On: https://github.com.evil/o/r/pull/12", + "Depends-On: http://github.com/o/r/pull/12", + "Depends-On: #12 extra", + ]) + assert.equal(stackDependency("o/r", body), null); }); +for (const dependency of ["#12", "https://github.com/o/r/pull/12"]) + test(`stack members with ${dependency} are validated against the stack root`, async () => { + const f = fixture(); + const top = { + ...f.source, + head: { + sha: sourceSha, + ref: "stack/u/feat/b--2", + repo: { full_name: "o/r" }, + }, + base: { ref: "stack/u/feat/a--1" }, + body: `Adds b.\n\nDepends-On: ${dependency}\n`, + }; + const bottom = { + ...f.source, + head: { + sha: sourceSha, + ref: "stack/u/feat/a--1", + repo: { full_name: "o/r" }, + }, + }; + const api = async (path) => { + if (path === "/repos/o/r/pulls/12") return bottom; + if (path === "/repos/o/r/pulls/13") return top; + return f.api(path); + }; + assert.deepEqual( + await validateBatch(f.input, api, f.commits, f.policy), + [12, 13], + ); + }); + test("rejects stack-like PRs whose chain does not reach the batch base", async () => { for (const [body, below] of [ // No marker: the queue keeps the literal stack branch as the target.