mirror of
https://github.com/vercel-labs/scriptc.git
synced 2026-12-06 04:56:15 +08:00
Warn about a shared FFI manifest's unused bindings, and document packaging (#4345)
* Warn about a shared FFI manifest's unused bindings, and document packaging - Warn about a shared FFI manifest's unused bindings, and document packaging. Co-authored-by: SergiiSharpov <25509495+SergiiSharpov@users.noreply.github.com> Co-authored-by: espetro <26749475+espetro@users.noreply.github.com> Fixes #3048 Fixes #3531 * Refuse a manifest name the program implements itself * ffi: keep an ordinary function named by an unused manifest entry * ffi: leave a scoped overload set to the program when the entry is unused * compiler: register the FFI name scan with the whole-program facts * ffi: poison a call only when its declaration was diagnosed --------- Co-authored-by: SergiiSharpov <25509495+SergiiSharpov@users.noreply.github.com> Co-authored-by: espetro <26749475+espetro@users.noreply.github.com>
This commit is contained in:
co-authored by
SergiiSharpov
espetro
parent
c1a2a96a5f
commit
bd1e35b7f2
@@ -54,6 +54,49 @@ Only direct calls to that exact declaration become native calls. A function with
|
||||
|
||||
For C++, export the function with `extern "C"` so it keeps an unmangled name. Pass the same manifest to `scriptc coverage` so the native calls count as compiled.
|
||||
|
||||
## Ship FFI in a package
|
||||
|
||||
A native binding package ships three things: the declarations, the manifest, and one static archive per target. The manifest's `libraries` paths resolve from the manifest's own directory, so archives that travel with the package work from wherever it is installed.
|
||||
|
||||
```text:my-native
|
||||
my-native/
|
||||
package.json
|
||||
index.d.ts
|
||||
ffi.darwin-arm64.json
|
||||
ffi.linux-x64-gnu.json
|
||||
lib/libnative-darwin-arm64.a
|
||||
lib/libnative-linux-x64-gnu.a
|
||||
```
|
||||
|
||||
Make the declarations global so a project can pull them in without a JavaScript import edge, and point `types` at the file:
|
||||
|
||||
```json:package.json
|
||||
{ "name": "my-native", "version": "1.0.0", "types": "index.d.ts" }
|
||||
```
|
||||
|
||||
```ts:index.d.ts
|
||||
declare function nativeScale(value: number): number;
|
||||
```
|
||||
|
||||
A manifest belongs to one target: `libraries` is a flat list, and the archive named there must match the build target. Ship one manifest per target whose entries name that target's archive.
|
||||
|
||||
The consuming project installs the package, adds a type reference in its entry, and builds with the manifest for its target:
|
||||
|
||||
```ts:main.ts
|
||||
/// <reference types="my-native" />
|
||||
console.log(nativeScale(21));
|
||||
```
|
||||
|
||||
```console
|
||||
$ scriptc build main.ts --ffi node_modules/my-native/ffi.darwin-arm64.json -o app
|
||||
```
|
||||
|
||||
Pass `--ffi` to `scriptc coverage` too, so the native calls count as compiled rather than as a runtime gap.
|
||||
|
||||
If you would rather not use a reference directive, declare the functions in the project's own source as signature-only `declare function`s and pass the same manifest; a binding matches its declaration by name.
|
||||
|
||||
Named imports of the package's functions are not supported. `import { nativeScale } from "my-native"` needs a JavaScript module to load, and a package that ships only declarations and native code has none; a package that also ships a JavaScript entry answers the import with that JavaScript function, not the native binding. Use the type reference or a local `declare function`.
|
||||
|
||||
<span id="replacing-a-node-api-addon" />
|
||||
|
||||
## Replace a Node-API addon
|
||||
@@ -412,7 +455,7 @@ On Darwin targets, a format 7 manifest may name system frameworks in `frameworks
|
||||
<dd>Format 7. Optional array of callback signatures for <code>node:ffi</code> <code>registerCallback</code>, each with <code>library</code>, <code>params</code>, <code>returns</code>, and an optional <code>capacity</code> from 1 to 256 (default 16).</dd>
|
||||
</dl>
|
||||
|
||||
Unknown fields, invalid ABI classes, duplicate names, and signature mismatches fail the build with an `SC5xxx` diagnostic.
|
||||
Unknown fields, invalid ABI classes, duplicate names, and signature mismatches fail the build with an `SC5xxx` diagnostic. An entry the program neither declares nor implements is not a failure: the build warns with `SC5005` and links the rest, so one manifest can list the bindings of several entry points and a program pays nothing for the ones it does not use. A name the program implements itself is different: the build refuses it (`SC5002`) rather than let a manifest claim calls the program's own function serves.
|
||||
|
||||
## Boundary rules and current limits
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ export const DIAGNOSTIC_CODES = {
|
||||
SC5002: "FFI binding is not an ambient function declaration",
|
||||
SC5003: "FFI signature does not match its native ABI",
|
||||
SC5004: "FFI native build failure",
|
||||
SC5005: "FFI manifest binding the program does not declare (warning)",
|
||||
SC6001: "divergence: width copy written or compared through",
|
||||
SC6002: "divergence: observed object key order",
|
||||
SC6003: "divergence: localeCompare outside the built-in collation",
|
||||
|
||||
@@ -64,8 +64,10 @@
|
||||
* SC5xxx native FFI: malformed manifests (SC5001), a configured
|
||||
* binding that is not an ambient function declaration
|
||||
* (SC5002), and a TypeScript signature that does not match its
|
||||
* declared native ABI classes (SC5003), and native toolchain
|
||||
* failures while applying a valid profile (SC5004)
|
||||
* declared native ABI classes (SC5003), native toolchain
|
||||
* failures while applying a valid profile (SC5004), and a
|
||||
* binding the program does not declare, which is a warning
|
||||
* (SC5005)
|
||||
* SC6xxx divergences: the program compiles, but the native binary can
|
||||
* behave differently from Node at this site — WARNINGS, never
|
||||
* build failures (coverage --fail-on=divergences opts in):
|
||||
@@ -1190,6 +1192,22 @@ export function ffiBindingDiag(name: string, detail: string, loc: SrcLoc): ScrDi
|
||||
};
|
||||
}
|
||||
|
||||
/** SC5005 — a manifest binding the program does not declare. A shared
|
||||
* manifest can list the bindings of several programs (a package's
|
||||
* `ffi.json` beside its declarations), so a program that declares none of
|
||||
* one entry's names is not broken: the binding is simply not linked into
|
||||
* it. The build says so and goes on. */
|
||||
export function ffiUnusedBindingDiag(name: string, loc: SrcLoc): ScrDiagnostic {
|
||||
return {
|
||||
code: "SC5005",
|
||||
message: `FFI manifest binding '${name}' is not declared in this program, so it is not bound`,
|
||||
loc,
|
||||
hint:
|
||||
`declare it as a signature-only ambient function to bind it, or keep the entry in a shared ` +
|
||||
`manifest for the programs that do; the build goes on`,
|
||||
};
|
||||
}
|
||||
|
||||
/** SC5003 — the ambient TypeScript signature and manifest ABI disagree. */
|
||||
export function ffiSignatureDiag(name: string, detail: string, loc: SrcLoc): ScrDiagnostic {
|
||||
return {
|
||||
|
||||
@@ -1524,6 +1524,8 @@ export interface LowererMode {
|
||||
/** Program-validated ambient declaration symbols for each FFI name.
|
||||
* Undefined in discovery's legacy call-local validation path. */
|
||||
ffiBindingSymbols?: ReadonlyMap<string, ReadonlySet<ts.Symbol>>;
|
||||
/** Symbols whose FFI declaration produced an error diagnostic. */
|
||||
ffiErrorSymbols?: ReadonlySet<ts.Symbol>;
|
||||
/** The build's outbound native FFI declarations. */
|
||||
ffiImports?: readonly IrFfiImport[];
|
||||
/** Statically resolved child_process.fork program roots, in stable target-id order. */
|
||||
@@ -2082,6 +2084,7 @@ function lowerToIrWithIslands(
|
||||
coverageReached,
|
||||
typeClaims,
|
||||
ffiBindingSymbols: ffiValidation.symbolsByName,
|
||||
ffiErrorSymbols: ffiValidation.errorSymbols,
|
||||
abortOnStreamFlags: abortReplacedPasses,
|
||||
});
|
||||
}
|
||||
@@ -2222,6 +2225,7 @@ function lowerToIrWithIslands(
|
||||
coverageReached,
|
||||
typeClaims,
|
||||
ffiBindingSymbols: ffiValidation.symbolsByName,
|
||||
ffiErrorSymbols: ffiValidation.errorSymbols,
|
||||
...(whole ? { wholeSlotDegradation: true } : {}),
|
||||
...(untyped || resultLowerer.untypedConstructors ? { untypedConstructors: true } : {}),
|
||||
...(dynamicClassValues.size > 0 ? { dynamicClassValues } : {}),
|
||||
@@ -2313,6 +2317,7 @@ function lowerToIrWithIslands(
|
||||
coverageReached,
|
||||
typeClaims,
|
||||
ffiBindingSymbols: ffiValidation.symbolsByName,
|
||||
ffiErrorSymbols: ffiValidation.errorSymbols,
|
||||
generalNodeStreams: true,
|
||||
// The general pass of a program that asks for checked-dynamic slots
|
||||
// is replaced by the pass that has them.
|
||||
@@ -2405,6 +2410,7 @@ function lowerToIrWithIslands(
|
||||
workerOnlyModules,
|
||||
workerModules,
|
||||
ffiBindingSymbols: ffiValidation.symbolsByName,
|
||||
ffiErrorSymbols: ffiValidation.errorSymbols,
|
||||
externalTypes,
|
||||
externalTypeSpecifiersByFile,
|
||||
tierMode,
|
||||
@@ -2490,6 +2496,7 @@ function lowerToIrWithIslands(
|
||||
found.loc.start === warning.loc.start,
|
||||
),
|
||||
),
|
||||
...ffiValidation.warnings,
|
||||
...resultLowerer.sharedModuleWarnings,
|
||||
...resultLowerer.islandWorkerWarnings,
|
||||
...resultLowerer.deferredRefusalWarnings,
|
||||
@@ -2671,6 +2678,7 @@ function lowerToIrWithIslands(
|
||||
workerOnlyModules,
|
||||
workerModules,
|
||||
ffiBindingSymbols: ffiValidation.symbolsByName,
|
||||
ffiErrorSymbols: ffiValidation.errorSymbols,
|
||||
externalTypes,
|
||||
externalTypeSpecifiersByFile,
|
||||
tierMode,
|
||||
@@ -6884,6 +6892,7 @@ export class Lowerer {
|
||||
"legacyDecoratorFiles",
|
||||
"libraryCallbacks",
|
||||
"ffiBindingSymbols",
|
||||
"ffiErrorSymbols",
|
||||
"priorRetriedSymbols",
|
||||
"wholeSlotDegradation",
|
||||
"untypedConstructors",
|
||||
@@ -7435,6 +7444,8 @@ export class Lowerer {
|
||||
readonly ffiImportsByName: ReadonlyMap<string, IrFfiImport>;
|
||||
/** Non-null after whole-program FFI declaration validation. */
|
||||
readonly ffiBindingSymbols: ReadonlyMap<string, ReadonlySet<ts.Symbol>> | null;
|
||||
/** Symbols whose FFI declaration produced an error diagnostic. */
|
||||
readonly ffiErrorSymbols: ReadonlySet<ts.Symbol> | null;
|
||||
/** Exact specifier mappings and their reverse declaration-file lookup. */
|
||||
readonly externalTypes: ReadonlyMap<string, string>;
|
||||
readonly externalTypeSpecifiersByFile: ReadonlyMap<string, readonly string[]>;
|
||||
@@ -8084,6 +8095,7 @@ export class Lowerer {
|
||||
this.abortOnStreamFlags = mode.abortOnStreamFlags === true;
|
||||
this.externalTypes = mode.externalTypes ?? new Map();
|
||||
this.ffiBindingSymbols = mode.ffiBindingSymbols ?? null;
|
||||
this.ffiErrorSymbols = mode.ffiErrorSymbols ?? null;
|
||||
this.ffiImports = mode.ffiImports ?? [];
|
||||
this.forkTargets = mode.forkTargets ?? [];
|
||||
this.frontendServices = mode.frontendServices;
|
||||
|
||||
@@ -23,6 +23,7 @@ import { locOf } from "../program.js";
|
||||
import {
|
||||
ffiBindingDiag,
|
||||
ffiSignatureDiag,
|
||||
ffiUnusedBindingDiag,
|
||||
libCallbackDiag,
|
||||
type ScrDiagnostic,
|
||||
} from "../../diagnostics/diagnostic.js";
|
||||
@@ -264,7 +265,14 @@ function ffiDeclarationDiagnostic(
|
||||
|
||||
export interface FfiValidationResult {
|
||||
diagnostics: ScrDiagnostic[];
|
||||
/** Manifest bindings the program does not declare (SC5005). Warnings:
|
||||
* a shared manifest may list several programs' bindings. */
|
||||
warnings: ScrDiagnostic[];
|
||||
symbolsByName: ReadonlyMap<string, ReadonlySet<ts.Symbol>>;
|
||||
/** The exact symbols whose declaration produced an error diagnostic. A
|
||||
* call that resolves to one of them is poisoned without a duplicate
|
||||
* diagnostic; every other unclaimed symbol keeps its normal lowering. */
|
||||
errorSymbols: ReadonlySet<ts.Symbol>;
|
||||
}
|
||||
|
||||
/** True when a library callback may claim declarations from this file.
|
||||
@@ -277,6 +285,33 @@ function libraryCallbackOwnsFile(lowerer: Lowerer, file: ts.SourceFile): boolean
|
||||
return !file.isDeclarationFile || (!lowerer.isStdlibFile(file) && !lowerer.isNpmFile(file));
|
||||
}
|
||||
|
||||
/** Whether the program declares `name` as anything other than a
|
||||
* signature-only ambient function: an implemented function, a class or a
|
||||
* variable. Such a name is a collision, not unused manifest capacity, and
|
||||
* a call of it must keep the implementation the program wrote rather than
|
||||
* be dropped (SC5002 says so). */
|
||||
function programDeclaresOrdinaryName(lowerer: Lowerer, name: string): boolean {
|
||||
for (const file of lowerer.program.getSourceFiles()) {
|
||||
if (lowerer.libraryCallbacks && !libraryCallbackOwnsFile(lowerer, file)) continue;
|
||||
let found = false;
|
||||
ts.walkPreorder(file, (node) => {
|
||||
if (found) return "skip";
|
||||
if (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) {
|
||||
if (node.body !== undefined && node.name !== undefined && node.name.text === name)
|
||||
found = true;
|
||||
return "skip";
|
||||
}
|
||||
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.name.text === name) {
|
||||
found = true;
|
||||
return "skip";
|
||||
}
|
||||
if (ts.isFunctionLike(node)) return "skip";
|
||||
});
|
||||
if (found) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Resolve and validate every configured outbound binding before emit.
|
||||
* Candidate declarations are signature-only functions bearing the manifest
|
||||
* name anywhere in the program. Multiple scoped declarations are all native
|
||||
@@ -286,7 +321,9 @@ function libraryCallbackOwnsFile(lowerer: Lowerer, file: ts.SourceFile): boolean
|
||||
* declaration files as authored callback surface. */
|
||||
export function validateFfiImports(lowerer: Lowerer): FfiValidationResult {
|
||||
const diagnostics: ScrDiagnostic[] = [];
|
||||
const warnings: ScrDiagnostic[] = [];
|
||||
const symbolsByName = new Map<string, ReadonlySet<ts.Symbol>>();
|
||||
const errorSymbols = new Set<ts.Symbol>();
|
||||
const configuredNames = new Set(
|
||||
lowerer.ffiImports
|
||||
.filter((binding) => binding.library === undefined)
|
||||
@@ -294,7 +331,7 @@ export function validateFfiImports(lowerer: Lowerer): FfiValidationResult {
|
||||
);
|
||||
const candidates = new Map<string, Map<ts.Symbol, ts.FunctionDeclaration>>();
|
||||
|
||||
if (configuredNames.size === 0) return { diagnostics, symbolsByName };
|
||||
if (configuredNames.size === 0) return { diagnostics, warnings, symbolsByName, errorSymbols };
|
||||
|
||||
for (const file of lowerer.program.getSourceFiles()) {
|
||||
if (lowerer.libraryCallbacks && !libraryCallbackOwnsFile(lowerer, file)) continue;
|
||||
@@ -325,19 +362,31 @@ export function validateFfiImports(lowerer: Lowerer): FfiValidationResult {
|
||||
if (binding.library !== undefined) continue;
|
||||
const bySymbol = candidates.get(binding.name);
|
||||
if (bySymbol === undefined || bySymbol.size === 0) {
|
||||
// A native-manifest binding with no declaration is a broken build
|
||||
// input. A library callback channel with no declaration is unused
|
||||
// CAPACITY: the registration symbol still dispatches it, nothing
|
||||
// calls it, and a later program revision may (a program that calls
|
||||
// the name without declaring it fails ordinary typechecking first).
|
||||
// No signature-only declaration. When the program implements the name
|
||||
// itself this is a collision, not unused capacity: a call of it must
|
||||
// keep the function the program wrote and never be silently dropped,
|
||||
// so the build fails as it did before shared manifests were allowed
|
||||
// (SC5002). Only a name the program neither declares nor implements
|
||||
// is unused capacity: a shared manifest (a package's ffi.json beside
|
||||
// the declarations every consumer may import) lists bindings for
|
||||
// several entry points, and a program that declares none of them is
|
||||
// not broken. A library callback channel with no declaration is
|
||||
// unused CAPACITY too: the registration symbol still dispatches it,
|
||||
// nothing calls it, and a later program revision may.
|
||||
if (!lowerer.libraryCallbacks) {
|
||||
diagnostics.push(
|
||||
ffiBindingDiag(
|
||||
binding.name,
|
||||
"the program has no signature-only function declaration with this name",
|
||||
{ file: lowerer.entry.fileName, start: 0, end: 0 },
|
||||
),
|
||||
);
|
||||
if (programDeclaresOrdinaryName(lowerer, binding.name)) {
|
||||
diagnostics.push(
|
||||
ffiBindingDiag(
|
||||
binding.name,
|
||||
"the program implements this name as an ordinary declaration, not a signature-only ambient function",
|
||||
{ file: lowerer.entry.fileName, start: 0, end: 0 },
|
||||
),
|
||||
);
|
||||
} else {
|
||||
warnings.push(
|
||||
ffiUnusedBindingDiag(binding.name, { file: lowerer.entry.fileName, start: 0, end: 0 }),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
// Preserve the distinction between unused capacity and a binding
|
||||
// whose program declaration was found but failed validation. The
|
||||
@@ -357,13 +406,14 @@ export function validateFfiImports(lowerer: Lowerer): FfiValidationResult {
|
||||
validSymbols.add(symbol);
|
||||
} else {
|
||||
diagnostics.push(diagnostic);
|
||||
errorSymbols.add(symbol);
|
||||
valid = false;
|
||||
}
|
||||
}
|
||||
if (valid) symbolsByName.set(binding.name, validSymbols);
|
||||
}
|
||||
|
||||
return { diagnostics, symbolsByName };
|
||||
return { diagnostics, warnings, symbolsByName, errorSymbols };
|
||||
}
|
||||
|
||||
/** A manifest-bound call of a signature-only ambient declaration. This
|
||||
@@ -422,9 +472,19 @@ export function lowerFfiCall(lowerer: Lowerer, expr: ts.CallExpression): IrExpr
|
||||
if (!symbol) bindingError("the call has no resolved TypeScript symbol");
|
||||
if (lowerer.ffiBindingSymbols !== null) {
|
||||
const validSymbols = lowerer.ffiBindingSymbols.get(binding.name);
|
||||
// No entry means the program-level pass already diagnosed this
|
||||
// binding. Poison the statement without duplicating that diagnostic.
|
||||
if (validSymbols === undefined) throw new PoisonError();
|
||||
if (validSymbols === undefined) {
|
||||
// No valid symbols for this name: the up-front pass either recorded an
|
||||
// error for a declaration of the resolved symbol, or treated the
|
||||
// entry as unused capacity. Only a symbol with a recorded error is
|
||||
// poisoned here, without duplicating that diagnostic. Every other
|
||||
// symbol (an import alias resolving to a library declaration, a
|
||||
// parameter, a nested function or overload implementation) is
|
||||
// unclaimed and keeps its normal lowering rather than being erased.
|
||||
if (lowerer.ffiErrorSymbols !== null && lowerer.ffiErrorSymbols.has(symbol)) {
|
||||
throw new PoisonError();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!validSymbols.has(symbol)) {
|
||||
if (lowerer.libraryCallbacks) {
|
||||
const declarations = symbol.declarations;
|
||||
|
||||
@@ -1040,6 +1040,12 @@ export const PROGRAM_SCANS: readonly ProgramScan[] = [
|
||||
"discovery",
|
||||
"the declarations that carry a configured binding's name",
|
||||
),
|
||||
scan(
|
||||
"frontend/lowering/native-ffi.ts#programDeclaresOrdinaryName",
|
||||
1,
|
||||
"discovery",
|
||||
"whether the program implements a manifest name as an ordinary declaration",
|
||||
),
|
||||
scan(
|
||||
"frontend/lowering/open-enumerations.ts#analyzeOpenEnumerations",
|
||||
2,
|
||||
|
||||
@@ -115,3 +115,91 @@ test("manifest-bound call initializers retain ffiCall IR and declaration storage
|
||||
records.some((record) => record.kind === "libCall" && record.fn === "global.undefRead"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("a shared manifest's binding the program does not declare is a warning, not a failure", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-ffi-unused-"));
|
||||
dirs.push(dir);
|
||||
const entry = join(dir, "unrelated.ts");
|
||||
const outDir = join(dir, ".scriptc");
|
||||
const profilePath = join(dir, "ffi.json");
|
||||
await writeFile(entry, 'console.log("unrelated");\n');
|
||||
await writeFile(
|
||||
profilePath,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "nativeScale", symbol: "native_scale", params: ["f64"], returns: "f64" }],
|
||||
libraries: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await compile(entry, {
|
||||
outDir,
|
||||
outPath: join(outDir, "unrelated.ir.json"),
|
||||
outputKind: "ir",
|
||||
ffiProfilePath: profilePath,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.warnings?.map((warning) => warning.code)).toEqual(["SC5005"]);
|
||||
expect(result.warnings?.[0]?.message).toContain("nativeScale");
|
||||
expect(result.warnings?.[0]?.message).toContain("not declared");
|
||||
}
|
||||
|
||||
// The same manifest against a program that declares the binding builds
|
||||
// without a warning: unused capacity is the only thing SC5005 reports.
|
||||
const declared = join(dir, "declared.ts");
|
||||
await writeFile(
|
||||
declared,
|
||||
"declare function nativeScale(value: number): number;\nconsole.log(nativeScale(21));\n",
|
||||
);
|
||||
const used = await compile(declared, {
|
||||
outDir,
|
||||
outPath: join(outDir, "declared.ir.json"),
|
||||
outputKind: "ir",
|
||||
ffiProfilePath: profilePath,
|
||||
});
|
||||
expect(used.ok).toBe(true);
|
||||
if (used.ok) expect(used.warnings ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
test("a manifest binding the program implements is a collision, not unused capacity", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "scriptc-ffi-collision-"));
|
||||
dirs.push(dir);
|
||||
const entry = join(dir, "guard.ts");
|
||||
const outDir = join(dir, ".scriptc");
|
||||
const profilePath = join(dir, "ffi.json");
|
||||
// The manifest names a function the program implements itself. The call
|
||||
// must keep that implementation: warning and poisoning the call would
|
||||
// silently erase a validation guard, so the build fails as SC5002 did
|
||||
// before shared manifests were allowed.
|
||||
await writeFile(
|
||||
entry,
|
||||
[
|
||||
"function nativeScale(value: number): number {",
|
||||
" return value * 2;",
|
||||
"}",
|
||||
"console.log(nativeScale(21));",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await writeFile(
|
||||
profilePath,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "nativeScale", symbol: "native_scale", params: ["f64"], returns: "f64" }],
|
||||
libraries: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await compile(entry, {
|
||||
outDir,
|
||||
outPath: join(outDir, "guard.ir.json"),
|
||||
outputKind: "ir",
|
||||
ffiProfilePath: profilePath,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.diagnostics.map((diagnostic) => diagnostic.code)).toEqual(["SC5002"]);
|
||||
expect(result.diagnostics[0]?.message).toContain("signature-only");
|
||||
}
|
||||
});
|
||||
|
||||
+250
-7
@@ -718,13 +718,6 @@ test.each([
|
||||
code: "SC5003",
|
||||
message: "parameter 1",
|
||||
},
|
||||
{
|
||||
id: "unused-missing",
|
||||
name: "an unused manifest binding with no source declaration",
|
||||
source: ["console.log('ok');", ""].join("\n"),
|
||||
code: "SC5002",
|
||||
message: "signature-only",
|
||||
},
|
||||
{
|
||||
id: "never-parameter",
|
||||
name: "an uninhabited TypeScript parameter presented as a native ABI slot",
|
||||
@@ -784,6 +777,34 @@ test.each([
|
||||
}
|
||||
});
|
||||
|
||||
test("a shared manifest may list bindings this program does not declare", async () => {
|
||||
const outDir = join(cacheRoot, "unused-binding");
|
||||
mkdirSync(outDir, { recursive: true });
|
||||
const entry = join(outDir, "main.ts");
|
||||
const profilePath = join(outDir, "profile.json");
|
||||
writeFileSync(entry, "console.log('ok');\n");
|
||||
writeFileSync(
|
||||
profilePath,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "nativeScale", symbol: "sf_scale", params: ["f64"], returns: "f64" }],
|
||||
}),
|
||||
);
|
||||
// IR emission types and lowers the program without a native toolchain, so
|
||||
// this covers the diagnostic path the build's warning rides on.
|
||||
const result = await compile(entry, {
|
||||
outDir,
|
||||
outPath: join(outDir, "main.ir.json"),
|
||||
outputKind: "ir",
|
||||
ffiProfilePath: profilePath,
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.warnings?.map((warning) => warning.code)).toEqual(["SC5005"]);
|
||||
expect(result.warnings?.[0]?.message).toContain("not declared");
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ id: "number-literal", type: "0", nativeClass: "f64", domain: "number", prefix: null },
|
||||
{
|
||||
@@ -1254,6 +1275,149 @@ test("a missing FFI symbol is an SC5004 diagnostic, not a rejected compile", asy
|
||||
}
|
||||
});
|
||||
|
||||
test("an unused manifest name does not claim a scoped function of the same name", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-ffi-unused-name-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
const profile = join(dir, "profile.json");
|
||||
try {
|
||||
writeFileSync(
|
||||
entry,
|
||||
[
|
||||
"function outer(): void {",
|
||||
' function guard(): void { throw new Error("denied"); }',
|
||||
" guard();",
|
||||
"}",
|
||||
"outer();",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
writeFileSync(
|
||||
profile,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "guard", symbol: "guard", params: [], returns: "void" }],
|
||||
libraries: [],
|
||||
system_libraries: [],
|
||||
}),
|
||||
);
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "program"),
|
||||
sanitize,
|
||||
ffiProfilePath: profile,
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
|
||||
}
|
||||
// The manifest entry is unused capacity; the call resolves to the
|
||||
// program's own function and must run, reaching the uncaught throw.
|
||||
const run = spawnSync(result.binaryPath, [], { encoding: "utf8" });
|
||||
expect(run.stdout).toBe("");
|
||||
expect(run.stderr).toContain("Error: denied");
|
||||
expect(run.status).not.toBe(0);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a scoped overload set named by an unused entry keeps its implementation", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-ffi-overload-name-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
const profile = join(dir, "profile.json");
|
||||
try {
|
||||
writeFileSync(
|
||||
profile,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "guard", symbol: "guard", params: ["string"], returns: "void" }],
|
||||
libraries: [],
|
||||
system_libraries: [],
|
||||
}),
|
||||
);
|
||||
writeFileSync(
|
||||
entry,
|
||||
[
|
||||
"function outer(): void {",
|
||||
" function guard(x: string): void;",
|
||||
' function guard(x: string): void { throw new Error("denied"); }',
|
||||
' guard("x");',
|
||||
"}",
|
||||
"outer();",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const scoped = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "program"),
|
||||
sanitize,
|
||||
ffiProfilePath: profile,
|
||||
});
|
||||
if (!scoped.ok) {
|
||||
throw new Error(scoped.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
|
||||
}
|
||||
// The overload set has an implementation, so the entry binds nothing and
|
||||
// the call must reach the program's own function.
|
||||
const run = spawnSync(scoped.binaryPath, [], { encoding: "utf8" });
|
||||
expect(run.stdout).toBe("");
|
||||
expect(run.stderr).toContain("Error: denied");
|
||||
expect(run.status).not.toBe(0);
|
||||
|
||||
// The same overload set at module scope is a diagnosed binding
|
||||
// collision, not an unused entry.
|
||||
writeFileSync(
|
||||
entry,
|
||||
[
|
||||
"function guard(x: string): void;",
|
||||
'function guard(x: string): void { throw new Error("denied"); }',
|
||||
'guard("x");',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
const top = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "program"),
|
||||
sanitize,
|
||||
ffiProfilePath: profile,
|
||||
});
|
||||
expect(top.ok).toBe(false);
|
||||
if (!top.ok) expect(top.diagnostics.map((d) => d.code)).toContain("SC5002");
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("a used manifest binding still intercepts its call", async () => {
|
||||
const dir = mkdtempSync(join(tmpdir(), "scriptc-ffi-used-binding-"));
|
||||
const entry = join(dir, "main.ts");
|
||||
const profile = join(dir, "profile.json");
|
||||
try {
|
||||
writeFileSync(
|
||||
entry,
|
||||
"declare function nativeScale(value: number): number;\nconsole.log(nativeScale(21));\n",
|
||||
);
|
||||
writeFileSync(
|
||||
profile,
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "nativeScale", symbol: "sf_scale", params: ["f64"], returns: "f64" }],
|
||||
libraries: [nativeArchive()],
|
||||
system_libraries: [],
|
||||
}),
|
||||
);
|
||||
const result = await compile(entry, {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "program"),
|
||||
sanitize,
|
||||
ffiProfilePath: profile,
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new Error(result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"));
|
||||
}
|
||||
expect(execFileSync(result.binaryPath, [], { encoding: "utf8" })).toBe("42\n");
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
// The sanitized lane compiles the generated C with -std=c11, which OpenCL
|
||||
// sources reject; the executable cache only exists on the plain lane.
|
||||
test.skipIf(sanitize)(
|
||||
@@ -1312,3 +1476,82 @@ test.skipIf(sanitize)(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("an unused manifest name does not claim an aliased builtin import", async () => {
|
||||
const root = mkdtempSync(join(tmpdir(), "scriptc-ffi-aliased-import-"));
|
||||
try {
|
||||
const cases: { name: string; files: Record<string, string> }[] = [
|
||||
{
|
||||
name: "named-alias",
|
||||
files: {
|
||||
"main.ts": 'import { ok as checkAuth } from "node:assert";\ncheckAuth(false);\n',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "reexported-alias",
|
||||
files: {
|
||||
"mid.ts": 'export { ok as checkAuth } from "node:assert";\n',
|
||||
"main.ts": 'import { checkAuth } from "./mid.ts";\ncheckAuth(false);\n',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "namespace-member",
|
||||
files: {
|
||||
"main.ts": 'import * as assert from "node:assert";\nassert.ok(false);\n',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "default-alias",
|
||||
files: {
|
||||
"main.ts": 'import checkAuth from "node:assert";\ncheckAuth(false);\n',
|
||||
},
|
||||
},
|
||||
];
|
||||
for (const entryCase of cases) {
|
||||
const dir = join(root, entryCase.name);
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const [file, text] of Object.entries(entryCase.files)) {
|
||||
writeFileSync(join(dir, file), text);
|
||||
}
|
||||
assertUnusedEntry(dir);
|
||||
const result = await compile(join(dir, "main.ts"), {
|
||||
outDir: dir,
|
||||
outPath: join(dir, "program"),
|
||||
sanitize,
|
||||
ffiProfilePath: join(dir, "profile.json"),
|
||||
});
|
||||
if (!result.ok) {
|
||||
throw new Error(
|
||||
`${entryCase.name}: ` +
|
||||
result.diagnostics.map((d) => `${d.code}: ${d.message}`).join("\n"),
|
||||
);
|
||||
}
|
||||
// The entry is unused capacity; the call must reach the imported
|
||||
// function and fail the assertion, exactly as Node does.
|
||||
const run = spawnSync(result.binaryPath, [], { encoding: "utf8" });
|
||||
expect(run.stdout, entryCase.name).toBe("");
|
||||
expect(run.stderr, entryCase.name).toContain("AssertionError");
|
||||
expect(run.status, entryCase.name).not.toBe(0);
|
||||
const oracle = spawnSync(process.execPath, ["--no-warnings", join(dir, "main.ts")], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
expect(oracle.status, entryCase.name).not.toBe(0);
|
||||
expect(oracle.stdout, entryCase.name).toBe("");
|
||||
expect(oracle.stderr, entryCase.name).toContain("AssertionError");
|
||||
}
|
||||
} finally {
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function assertUnusedEntry(dir: string): void {
|
||||
writeFileSync(
|
||||
join(dir, "profile.json"),
|
||||
JSON.stringify({
|
||||
ffi_format: 1,
|
||||
functions: [{ name: "checkAuth", symbol: "checkAuth", params: [], returns: "void" }],
|
||||
libraries: [],
|
||||
system_libraries: [],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user