test(fuzz): add deterministic fuzz harness for parser, kitchen, analyzer and formatter #196
32 changed files with 1567 additions and 23 deletions
|
|
@ -19,10 +19,7 @@ import { checkParse } from "./src/checks/parse";
|
|||
import { buildTrustedVocabulary, checkConstructVocabulary } from "./src/checks/construct-vocabulary";
|
||||
import { checkWarnings } from "./src/checks/warnings";
|
||||
import { missingConfiguredPaths, REPO_ROOT } from "./src/config";
|
||||
import { extractConformanceCases, extractPhysicalFixtures } from "./src/extract/fixtures";
|
||||
import { extractInlineTestLiterals } from "./src/extract/inline-tests";
|
||||
import { extractNonTrustedDocsFences, extractTrustedCorpusFences } from "./src/extract/markdown-fences";
|
||||
import { extractTmpfileWrites } from "./src/extract/tmpfile-writes";
|
||||
import { collectCorpusParts } from "./src/corpus";
|
||||
import { printReport } from "./src/report";
|
||||
import { runSelfTest } from "./src/self-test";
|
||||
import type { Finding, Snippet } from "./src/types";
|
||||
|
|
@ -49,20 +46,10 @@ if (missing.length > 0) {
|
|||
}
|
||||
|
||||
// 1. Extraction
|
||||
const trustedFences = extractTrustedCorpusFences();
|
||||
const nonTrustedDocsFences = extractNonTrustedDocsFences();
|
||||
const physicalFixtures = extractPhysicalFixtures();
|
||||
const conformanceCases = extractConformanceCases();
|
||||
const { snippets: inlineLiterals, skipped } = extractInlineTestLiterals();
|
||||
const tmpfileWrites = extractTmpfileWrites();
|
||||
|
||||
const auditTargets: Snippet[] = [
|
||||
...nonTrustedDocsFences,
|
||||
...physicalFixtures,
|
||||
...conformanceCases,
|
||||
...inlineLiterals,
|
||||
...tmpfileWrites,
|
||||
].filter(matchesFilter);
|
||||
const corpus = collectCorpusParts();
|
||||
const trustedFences = corpus.trusted;
|
||||
const skipped = corpus.skipped;
|
||||
const auditTargets: Snippet[] = corpus.targets.filter(matchesFilter);
|
||||
|
||||
// 2. Calibration — must run before any format-diff finding below is trusted.
|
||||
const calibration = calibrateFormatter(trustedFences);
|
||||
|
|
@ -98,7 +85,7 @@ for (const snippet of auditTargets) {
|
|||
}
|
||||
|
||||
// 5. Self-test — validates the tool's own coverage against known mistakes.
|
||||
const selfTest = runSelfTest(trustedVocabulary);
|
||||
const selfTest = runSelfTest(trustedVocabulary, corpus.selfTest);
|
||||
|
||||
const report = {
|
||||
calibration,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,9 @@
|
|||
"version": "1.5.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./corpus": "./src/corpus.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"audit": "bun run audit.ts",
|
||||
"audit:json": "bun run audit.ts --json"
|
||||
|
|
|
|||
44
audit/src/corpus.ts
Normal file
44
audit/src/corpus.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { extractConformanceCases, extractPhysicalFixtures } from "./extract/fixtures";
|
||||
import { extractInlineTestLiterals } from "./extract/inline-tests";
|
||||
import { extractNonTrustedDocsFences, extractTrustedCorpusFences } from "./extract/markdown-fences";
|
||||
import { extractSelfTestSnippets } from "./extract/self-test-cases";
|
||||
import { extractTmpfileWrites } from "./extract/tmpfile-writes";
|
||||
import type { SkippedExtraction, Snippet } from "./types";
|
||||
|
||||
/** Every piece of Gram source in the repo, grouped by the role the audit gives it. */
|
||||
export interface CorpusParts {
|
||||
/** reference/syntax pages (EN+FR) ✅ fences: the known-good vocabulary. */
|
||||
trusted: Snippet[];
|
||||
/** What the audit triages: docs fences, fixtures, conformance cases, test literals. */
|
||||
targets: Snippet[];
|
||||
/** ai-generation-notes ❌/✅ pairs, checked against the audit's own coverage. */
|
||||
selfTest: { bad: Snippet[]; good: Snippet[]; staleness: string | null };
|
||||
/** Inline test literals the extractor could not read statically. */
|
||||
skipped: SkippedExtraction[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The single collector of Gram sources in the repo, shared by the content
|
||||
* audit (`audit.ts`) and the fuzzer (`fuzz/`): no list of paths lives twice.
|
||||
*/
|
||||
export function collectCorpusParts(): CorpusParts {
|
||||
const { snippets: inlineLiterals, skipped } = extractInlineTestLiterals();
|
||||
return {
|
||||
trusted: extractTrustedCorpusFences(),
|
||||
targets: [
|
||||
...extractNonTrustedDocsFences(),
|
||||
...extractPhysicalFixtures(),
|
||||
...extractConformanceCases(),
|
||||
...inlineLiterals,
|
||||
...extractTmpfileWrites(),
|
||||
],
|
||||
selfTest: extractSelfTestSnippets(),
|
||||
skipped,
|
||||
};
|
||||
}
|
||||
|
||||
/** Every snippet, whatever its role, invalid ones included. */
|
||||
export function collectCorpus(): Snippet[] {
|
||||
const { trusted, targets, selfTest } = collectCorpusParts();
|
||||
return [...trusted, ...targets, ...selfTest.bad, ...selfTest.good];
|
||||
}
|
||||
|
|
@ -1,19 +1,22 @@
|
|||
import { getAST } from "@gram-lang/parser";
|
||||
import { extractSelfTestSnippets } from "./extract/self-test-cases";
|
||||
import { checkConstructVocabulary, type TrustedVocabulary } from "./checks/construct-vocabulary";
|
||||
import { checkFormatDiff } from "./checks/format-diff";
|
||||
import { checkWarnings } from "./checks/warnings";
|
||||
import type { CorpusParts } from "./corpus";
|
||||
import { extractSelfTestSnippets } from "./extract/self-test-cases";
|
||||
import type { Finding } from "./types";
|
||||
|
||||
// Runs checks 1-4 against every ai-generation-notes ❌/✅ pair. This
|
||||
// validates the AUDIT TOOL's own coverage, not new content: a ❌ example that
|
||||
// trips zero checks is a gap in the tool (it can't catch a known mistake); a
|
||||
// ✅ example that trips any check is a false positive on doc-sanctioned Gram.
|
||||
export function runSelfTest(trusted: TrustedVocabulary): {
|
||||
export function runSelfTest(
|
||||
trusted: TrustedVocabulary,
|
||||
{ bad, good, staleness }: CorpusParts["selfTest"] = extractSelfTestSnippets(),
|
||||
): {
|
||||
findings: Finding[];
|
||||
staleness: string | null;
|
||||
} {
|
||||
const { bad, good, staleness } = extractSelfTestSnippets();
|
||||
const findings: Finding[] = [];
|
||||
|
||||
for (const snippet of bad) {
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@
|
|||
"packages/*/src/**",
|
||||
"packages/*/tests/**",
|
||||
"conformance/*.ts",
|
||||
"fuzz/**/*.ts",
|
||||
"!**/*.gram",
|
||||
"!**/grammar-content.ts",
|
||||
"!**/*.svg",
|
||||
|
|
|
|||
17
bun.lock
17
bun.lock
|
|
@ -47,6 +47,21 @@
|
|||
"@types/node": "^26.1.1",
|
||||
},
|
||||
},
|
||||
"fuzz": {
|
||||
"name": "@gram-lang/fuzz",
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@gram-lang/analyzer": "workspace:*",
|
||||
"@gram-lang/audit": "workspace:*",
|
||||
"@gram-lang/format": "workspace:*",
|
||||
"@gram-lang/kitchen": "workspace:*",
|
||||
"@gram-lang/parser": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.4",
|
||||
"typescript": "^6.0.3",
|
||||
},
|
||||
},
|
||||
"packages/analyzer": {
|
||||
"name": "@gram-lang/analyzer",
|
||||
"version": "1.5.0",
|
||||
|
|
@ -621,6 +636,8 @@
|
|||
|
||||
"@gram-lang/format": ["@gram-lang/format@workspace:packages/format"],
|
||||
|
||||
"@gram-lang/fuzz": ["@gram-lang/fuzz@workspace:fuzz"],
|
||||
|
||||
"@gram-lang/i18n": ["@gram-lang/i18n@workspace:packages/i18n"],
|
||||
|
||||
"@gram-lang/kitchen": ["@gram-lang/kitchen@workspace:packages/kitchen"],
|
||||
|
|
|
|||
102
fuzz/cli.ts
Normal file
102
fuzz/cli.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
#!/usr/bin/env bun
|
||||
/**
|
||||
* Deterministic fuzzing of the parser, the compiler, the analyzer and the formatter.
|
||||
*
|
||||
* bun run fuzz # 2 000 inputs, random seed (printed)
|
||||
* bun run fuzz --seed 1735549293 --iterations 200000 --minimize
|
||||
* bun run fuzz --seed 1735549293 --index 4211 # replay one input
|
||||
* bun run fuzz --corpus # the unmutated corpus only
|
||||
* bun run fuzz --invariant format-idempotent --invariant format-no-throw
|
||||
*/
|
||||
import { parseArgs } from "node:util";
|
||||
import { fuzzCorpus } from "./src/corpus";
|
||||
import { INVARIANTS, invariantsById } from "./src/invariants";
|
||||
import { knownFailures } from "./src/known-failures";
|
||||
import {
|
||||
checkInput,
|
||||
type Finding,
|
||||
generateInput,
|
||||
runFuzz,
|
||||
scanCorpus,
|
||||
} from "./src/run";
|
||||
import { shrink } from "./src/shrink";
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
seed: { type: "string" },
|
||||
iterations: { type: "string", default: "2000" },
|
||||
index: { type: "string" },
|
||||
invariant: { type: "string", multiple: true },
|
||||
minimize: { type: "boolean", default: false },
|
||||
corpus: { type: "boolean", default: false },
|
||||
},
|
||||
});
|
||||
|
||||
const seed =
|
||||
values.seed !== undefined
|
||||
? Number(values.seed) >>> 0
|
||||
: Math.floor(Math.random() * 0x100000000);
|
||||
const iterations = Number(values.iterations);
|
||||
const invariants = values.invariant?.length
|
||||
? invariantsById(values.invariant)
|
||||
: INVARIANTS;
|
||||
const corpus = fuzzCorpus();
|
||||
|
||||
if (values.index !== undefined) {
|
||||
const generated = generateInput(seed, Number(values.index), corpus);
|
||||
console.log(
|
||||
`seed ${seed}, index ${generated.index}, from ${generated.corpusId}`,
|
||||
);
|
||||
console.log(`mutations: ${generated.mutations.join(", ")}`);
|
||||
console.log(`input: ${JSON.stringify(generated.input)}`);
|
||||
const violations = checkInput(generated.input, invariants);
|
||||
for (const v of violations)
|
||||
console.log(`\n✗ ${v.signature}\n${v.stack ?? v.message}`);
|
||||
if (violations.length === 0) console.log("\n✓ no violation");
|
||||
process.exit(violations.length > 0 ? 1 : 0);
|
||||
}
|
||||
|
||||
const label = values.corpus
|
||||
? `${corpus.length} corpus snippets, unmutated`
|
||||
: `seed ${seed}, ${iterations} inputs`;
|
||||
console.log(`fuzz: ${label}, ${invariants.length} invariants`);
|
||||
const start = performance.now();
|
||||
const findings: Finding[] = values.corpus
|
||||
? scanCorpus(corpus, invariants)
|
||||
: runFuzz({
|
||||
seed,
|
||||
iterations,
|
||||
corpus,
|
||||
invariants,
|
||||
onInput: (i) => {
|
||||
if (process.stdout.isTTY && i % 1000 === 999)
|
||||
process.stdout.write(`\r ${i + 1}/${iterations}`);
|
||||
},
|
||||
});
|
||||
if (process.stdout.isTTY) process.stdout.write("\r");
|
||||
console.log(`done in ${((performance.now() - start) / 1000).toFixed(1)} s\n`);
|
||||
|
||||
const known = new Map(knownFailures().map((k) => [k.signature, k]));
|
||||
let fresh = 0;
|
||||
for (const f of findings) {
|
||||
const k = known.get(f.signature);
|
||||
if (!k) fresh++;
|
||||
console.log(
|
||||
`${k ? "known" : "NEW "} ×${f.count} ${f.signature}${k ? ` (${k.issue})` : ""}`,
|
||||
);
|
||||
if (!values.corpus)
|
||||
console.log(
|
||||
` replay: bun run fuzz --seed ${seed} --index ${f.index}`,
|
||||
);
|
||||
else console.log(` from: ${f.corpusId}`);
|
||||
const input = values.minimize
|
||||
? shrink(f.input, (c) =>
|
||||
checkInput(c, invariants).some((v) => v.signature === f.signature),
|
||||
)
|
||||
: f.input;
|
||||
console.log(
|
||||
` input${values.minimize ? " (minimized)" : ""}: ${JSON.stringify(input).slice(0, 400)}`,
|
||||
);
|
||||
}
|
||||
console.log(`\n${findings.length} signature(s), ${fresh} new`);
|
||||
process.exit(fresh > 0 ? 1 : 0);
|
||||
146
fuzz/known-failures.json
Normal file
146
fuzz/known-failures.json
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
[
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.activeBreakdown",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "## {\n}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.registry.ingredients",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "@m\n{g}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].ingredients[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "@n\n{1}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | formatted source no longer parses | parser:header_trailing",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "## {\n~{0}."
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.miseEnPlace[].duration",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "->&dough\n\n## l\n@t\n{0%&dough}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.prepBreakdown[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "@s\n{}(n)"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.schedule.blocks[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "~{5m}{\n\n~{2m}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | formatted source no longer parses | parser:throwBracesError",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "@r\n{"
|
||||
},
|
||||
{
|
||||
"signature": "format-idempotent | second pass reported changes on an unchanged output",
|
||||
"invariant": "format-idempotent",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "{1\n##}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.miseEnPlace[].section",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/197",
|
||||
"example": "## {\n## \n## n\n@r}"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].title",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/201",
|
||||
"example": "## {1,0}"
|
||||
},
|
||||
{
|
||||
"signature": "format-idempotent | second pass changed the output (compositeSeparatorSpacing)",
|
||||
"invariant": "format-idempotent",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/204",
|
||||
"example": "<\t@"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.tasks.tasks[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/208",
|
||||
"example": "&@S"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.warnings[].item",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/208",
|
||||
"example": "~@F{}"
|
||||
},
|
||||
{
|
||||
"signature": "compile-no-throw | compile threw Error: MULTIPLE_BAKERS_PERCENTAGE: Only one ingredient can be marked with the baker's percentage (*) modifier in a recipe. | kitchen:<anonymous>",
|
||||
"invariant": "compile-no-throw",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/198",
|
||||
"example": "@*n @*b"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/205",
|
||||
"example": "## "
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[].id",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/205",
|
||||
"example": "## \n#p"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.cookware[]._usageId",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/205",
|
||||
"example": "## \n#p|#s"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.sections[].steps[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/200",
|
||||
"example": "e\r"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.activeBreakdown[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/200",
|
||||
"example": ".\n \n["
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.metrics.prepBreakdown",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/200",
|
||||
"example": "@\r"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | formatted source no longer parses | parser:getAST",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/199",
|
||||
"example": ""
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.meta",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/206",
|
||||
"example": "---\ntitle:\n---"
|
||||
},
|
||||
{
|
||||
"signature": "format-preserves-meaning | compilation differs after formatting at $.sections[]",
|
||||
"invariant": "format-preserves-meaning",
|
||||
"issue": "https://git.gram-lang.org/gram-lang/gram/issues/207",
|
||||
"example": "@use \"a\" as &a\n//"
|
||||
}
|
||||
]
|
||||
21
fuzz/package.json
Normal file
21
fuzz/package.json
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"name": "@gram-lang/fuzz",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"fuzz": "bun run cli.ts",
|
||||
"typecheck": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@gram-lang/analyzer": "workspace:*",
|
||||
"@gram-lang/audit": "workspace:*",
|
||||
"@gram-lang/format": "workspace:*",
|
||||
"@gram-lang/kitchen": "workspace:*",
|
||||
"@gram-lang/parser": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "1.4.4",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
0
fuzz/regressions/.gitkeep
Normal file
0
fuzz/regressions/.gitkeep
Normal file
20
fuzz/src/corpus.ts
Normal file
20
fuzz/src/corpus.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import { collectCorpus } from "@gram-lang/audit/corpus";
|
||||
import type { CorpusEntry } from "./run";
|
||||
|
||||
let cached: CorpusEntry[] | null = null;
|
||||
|
||||
/**
|
||||
* The fuzz seeds: every Gram snippet the audit collects, invalid ones
|
||||
* included (they are the most useful starting points), one per content.
|
||||
*/
|
||||
export function fuzzCorpus(): CorpusEntry[] {
|
||||
if (cached) return cached;
|
||||
const seen = new Set<string>();
|
||||
cached = [];
|
||||
for (const s of collectCorpus()) {
|
||||
if (seen.has(s.content)) continue;
|
||||
seen.add(s.content);
|
||||
cached.push({ id: s.id, content: s.content });
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
22
fuzz/src/database.ts
Normal file
22
fuzz/src/database.ts
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { IngredientData } from "@gram-lang/analyzer";
|
||||
|
||||
/**
|
||||
* The playground's example database: the one the docs run `analyze()` with on
|
||||
* every keystroke, so the one a real document meets.
|
||||
*/
|
||||
const PATH = join(
|
||||
import.meta.dir,
|
||||
"../../packages/docs/src/components/playground/ingredients.yaml",
|
||||
);
|
||||
|
||||
let cached: Record<string, IngredientData> | null = null;
|
||||
|
||||
export function exampleDatabase(): Record<string, IngredientData> {
|
||||
cached ??= Bun.YAML.parse(readFileSync(PATH, "utf-8")) as Record<
|
||||
string,
|
||||
IngredientData
|
||||
>;
|
||||
return cached;
|
||||
}
|
||||
199
fuzz/src/invariants.ts
Normal file
199
fuzz/src/invariants.ts
Normal file
|
|
@ -0,0 +1,199 @@
|
|||
import { hasChanges } from "@gram-lang/format";
|
||||
import { GramParseError } from "@gram-lang/parser";
|
||||
import {
|
||||
firstDifference,
|
||||
MEANING_REPAIRS,
|
||||
normalize,
|
||||
pathShape,
|
||||
} from "./normalize";
|
||||
import { type Outcome, Prepared } from "./prepared";
|
||||
import { signatureOf } from "./signature";
|
||||
|
||||
export interface Violation {
|
||||
invariant: string;
|
||||
message: string;
|
||||
signature: string;
|
||||
stack?: string;
|
||||
}
|
||||
|
||||
export interface Invariant {
|
||||
id: string;
|
||||
check(input: Prepared): Violation | null;
|
||||
}
|
||||
|
||||
function violation(
|
||||
invariant: string,
|
||||
message: string,
|
||||
error?: unknown,
|
||||
): Violation {
|
||||
return {
|
||||
invariant,
|
||||
message,
|
||||
signature: signatureOf(invariant, message, error),
|
||||
...(error instanceof Error && error.stack ? { stack: error.stack } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function describe(error: unknown): string {
|
||||
return error instanceof Error
|
||||
? `${error.name}: ${error.message}`
|
||||
: String(error);
|
||||
}
|
||||
|
||||
/** A stage that threw where it must not. */
|
||||
function noThrow(
|
||||
id: string,
|
||||
outcome: Outcome<unknown> | null,
|
||||
stage: string,
|
||||
): Violation | null {
|
||||
if (!outcome || outcome.ok) return null;
|
||||
return violation(
|
||||
id,
|
||||
`${stage} threw ${describe(outcome.error)}`,
|
||||
outcome.error,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The time an input may take through parse + compile + format, in ms. Wide on
|
||||
* purpose: it catches a super-linear blow-up, not a slow CI runner.
|
||||
*/
|
||||
export function timeBudget(length: number): number {
|
||||
return 200 + 0.05 * length;
|
||||
}
|
||||
|
||||
export const INVARIANTS: readonly Invariant[] = [
|
||||
{
|
||||
id: "parse-contract",
|
||||
check: ({ parse, source }) => {
|
||||
if (parse.ok) return null;
|
||||
const e = parse.error;
|
||||
if (!(e instanceof GramParseError)) {
|
||||
return violation(
|
||||
"parse-contract",
|
||||
`getAST threw ${describe(e)} instead of GramParseError`,
|
||||
e,
|
||||
);
|
||||
}
|
||||
if (
|
||||
!Number.isInteger(e.offset) ||
|
||||
e.offset < 0 ||
|
||||
e.offset > source.length
|
||||
) {
|
||||
return violation(
|
||||
"parse-contract",
|
||||
"GramParseError.offset outside [0, source.length]",
|
||||
);
|
||||
}
|
||||
if (typeof e.expected !== "string" || e.expected.trim() === "") {
|
||||
return violation("parse-contract", "GramParseError.expected is empty");
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "compile-no-throw",
|
||||
check: (p) => noThrow("compile-no-throw", p.compile, "compile"),
|
||||
},
|
||||
{
|
||||
id: "analyze-no-throw",
|
||||
check: (p) => noThrow("analyze-no-throw", p.analyze, "analyze"),
|
||||
},
|
||||
{
|
||||
id: "format-no-throw",
|
||||
check: (p) => noThrow("format-no-throw", p.format, "formatGram"),
|
||||
},
|
||||
{
|
||||
id: "format-idempotent",
|
||||
check: (p) => {
|
||||
const once = p.format;
|
||||
const twice = p.reformat;
|
||||
if (!once.ok || !twice) return null;
|
||||
if (!twice.ok)
|
||||
return violation(
|
||||
"format-idempotent",
|
||||
`second formatGram threw ${describe(twice.error)}`,
|
||||
twice.error,
|
||||
);
|
||||
if (twice.value.content !== once.value.content) {
|
||||
const rules = Object.entries(twice.value.changes)
|
||||
.filter(([, n]) => n !== 0 && n !== false)
|
||||
.map(([rule]) => rule);
|
||||
return violation(
|
||||
"format-idempotent",
|
||||
`second pass changed the output (${rules.join(", ") || "no rule reported"})`,
|
||||
);
|
||||
}
|
||||
if (hasChanges(twice.value.changes)) {
|
||||
return violation(
|
||||
"format-idempotent",
|
||||
"second pass reported changes on an unchanged output",
|
||||
);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "format-preserves-meaning",
|
||||
check: (p) => {
|
||||
// An input that does not parse may be "repaired" by the formatter:
|
||||
// not a violation. One whose compilation throws is I2's business.
|
||||
if (!p.parse.ok || !p.compile?.ok) return null;
|
||||
const after = p.formattedCompile;
|
||||
if (!after || !p.format.ok) return null;
|
||||
const changes = p.format.value.changes;
|
||||
if (MEANING_REPAIRS.some((rule) => changes[rule])) return null;
|
||||
if (!after.parse.ok) {
|
||||
return violation(
|
||||
"format-preserves-meaning",
|
||||
"formatted source no longer parses",
|
||||
after.parse.error,
|
||||
);
|
||||
}
|
||||
if (!after.compile?.ok) {
|
||||
return violation(
|
||||
"format-preserves-meaning",
|
||||
"formatted source no longer compiles",
|
||||
after.compile?.error,
|
||||
);
|
||||
}
|
||||
const diff = firstDifference(
|
||||
normalize(p.compile.value),
|
||||
normalize(after.compile.value),
|
||||
);
|
||||
if (!diff) return null;
|
||||
return violation(
|
||||
"format-preserves-meaning",
|
||||
`compilation differs after formatting at ${pathShape(diff)}`,
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "time-budget",
|
||||
check: (p) => {
|
||||
const elapsed = (q: Prepared) =>
|
||||
q.parse.ms + (q.compile?.ms ?? 0) + q.format.ms;
|
||||
const budget = timeBudget(p.source.length);
|
||||
let ms = elapsed(p);
|
||||
// A GC pause or a cold JIT is not a blow-up: measure twice more, keep the best.
|
||||
for (let i = 0; i < 2 && ms > budget; i++)
|
||||
ms = Math.min(ms, elapsed(new Prepared(p.source, p.database)));
|
||||
if (ms <= budget) return null;
|
||||
return violation(
|
||||
"time-budget",
|
||||
`parse + compile + format took ${Math.round(ms)} ms, budget ${Math.round(budget)} ms`,
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export function invariantsById(ids: readonly string[]): Invariant[] {
|
||||
return ids.map((id) => {
|
||||
const inv = INVARIANTS.find((i) => i.id === id);
|
||||
if (!inv)
|
||||
throw new Error(
|
||||
`unknown invariant "${id}" (known: ${INVARIANTS.map((i) => i.id).join(", ")})`,
|
||||
);
|
||||
return inv;
|
||||
});
|
||||
}
|
||||
27
fuzz/src/known-failures.ts
Normal file
27
fuzz/src/known-failures.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
/**
|
||||
* The ratchet: violations already found and not fixed yet, each tied to an
|
||||
* issue. The fuzz test fails on a violation missing from this list, and on
|
||||
* an entry whose `example` no longer fails: the file can only shrink.
|
||||
*/
|
||||
export interface KnownFailure {
|
||||
signature: string;
|
||||
invariant: string;
|
||||
/** Forgejo issue tracking the fix. */
|
||||
issue: string;
|
||||
/** A minimized input that triggers it. */
|
||||
example: string;
|
||||
}
|
||||
|
||||
export const KNOWN_FAILURES_PATH = join(
|
||||
import.meta.dir,
|
||||
"../known-failures.json",
|
||||
);
|
||||
|
||||
export function knownFailures(): KnownFailure[] {
|
||||
return JSON.parse(
|
||||
readFileSync(KNOWN_FAILURES_PATH, "utf-8"),
|
||||
) as KnownFailure[];
|
||||
}
|
||||
151
fuzz/src/mutators.ts
Normal file
151
fuzz/src/mutators.ts
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
import type { Rng } from "./prng";
|
||||
|
||||
export interface MutationContext {
|
||||
/** Other sources to graft fragments from (crossover). */
|
||||
donors: readonly string[];
|
||||
}
|
||||
|
||||
export interface Mutator {
|
||||
id: string;
|
||||
/** Relative frequency among the mutators. */
|
||||
weight: number;
|
||||
apply(source: string, rng: Rng, ctx: MutationContext): string;
|
||||
}
|
||||
|
||||
const SYNTAX_CHARS = [
|
||||
"{",
|
||||
"}",
|
||||
"/",
|
||||
"|",
|
||||
"&",
|
||||
"@",
|
||||
"#",
|
||||
"~",
|
||||
"^",
|
||||
"=",
|
||||
"(",
|
||||
")",
|
||||
"[",
|
||||
"]",
|
||||
"<",
|
||||
">",
|
||||
"%",
|
||||
"?",
|
||||
"-",
|
||||
"+",
|
||||
"*",
|
||||
":",
|
||||
"'",
|
||||
'"',
|
||||
] as const;
|
||||
|
||||
const BREAKS = ["\n", "\n\n", "\r\n", "\r"] as const;
|
||||
|
||||
const TRICKY_UNICODE = [
|
||||
" ", // no-break space
|
||||
"", // zero-width space
|
||||
"", // BOM
|
||||
"", // right-to-left mark
|
||||
"́", // combining acute accent
|
||||
"👩🍳", // multi-code-point emoji (ZWJ sequence)
|
||||
"\0",
|
||||
"\ud83d", // lone high surrogate
|
||||
"\udc00", // lone low surrogate
|
||||
] as const;
|
||||
|
||||
const at = (source: string, rng: Rng) => rng.int(0, source.length);
|
||||
const insert = (source: string, index: number, text: string) =>
|
||||
source.slice(0, index) + text + source.slice(index);
|
||||
|
||||
export const MUTATORS: readonly Mutator[] = [
|
||||
{
|
||||
id: "insert-syntax-char",
|
||||
weight: 5,
|
||||
apply: (s, rng) => insert(s, at(s, rng), rng.pick(SYNTAX_CHARS)),
|
||||
},
|
||||
{
|
||||
id: "insert-break",
|
||||
weight: 2,
|
||||
apply: (s, rng) => insert(s, at(s, rng), rng.pick(BREAKS)),
|
||||
},
|
||||
{
|
||||
id: "insert-unicode",
|
||||
weight: 2,
|
||||
apply: (s, rng) => insert(s, at(s, rng), rng.pick(TRICKY_UNICODE)),
|
||||
},
|
||||
{
|
||||
id: "delete-range",
|
||||
weight: 3,
|
||||
apply: (s, rng) => {
|
||||
const start = at(s, rng);
|
||||
return s.slice(0, start) + s.slice(start + rng.int(1, 8));
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "duplicate-line",
|
||||
weight: 1,
|
||||
apply: (s, rng) => {
|
||||
const lines = s.split("\n");
|
||||
const i = rng.int(0, lines.length - 1);
|
||||
lines.splice(i, 0, lines[i] ?? "");
|
||||
return lines.join("\n");
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "swap-lines",
|
||||
weight: 1,
|
||||
apply: (s, rng) => {
|
||||
const lines = s.split("\n");
|
||||
const i = rng.int(0, lines.length - 1);
|
||||
const j = rng.int(0, lines.length - 1);
|
||||
[lines[i], lines[j]] = [lines[j] ?? "", lines[i] ?? ""];
|
||||
return lines.join("\n");
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "truncate",
|
||||
weight: 1,
|
||||
apply: (s, rng) => s.slice(0, at(s, rng)),
|
||||
},
|
||||
{
|
||||
id: "crossover",
|
||||
weight: 2,
|
||||
apply: (s, rng, ctx) => {
|
||||
if (ctx.donors.length === 0) return s;
|
||||
const donor = rng.pick(ctx.donors).split("\n");
|
||||
const from = rng.int(0, donor.length - 1);
|
||||
const fragment = donor.slice(from, from + rng.int(1, 4));
|
||||
const lines = s.split("\n");
|
||||
lines.splice(rng.int(0, lines.length), 0, ...fragment);
|
||||
return lines.join("\n");
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function pickWeighted(rng: Rng, mutators: readonly Mutator[]): Mutator {
|
||||
const total = mutators.reduce((sum, m) => sum + m.weight, 0);
|
||||
let roll = rng.next() * total;
|
||||
for (const m of mutators) {
|
||||
roll -= m.weight;
|
||||
if (roll < 0) return m;
|
||||
}
|
||||
return mutators[mutators.length - 1] as Mutator;
|
||||
}
|
||||
|
||||
/** Stacks 1 to 4 mutations on `source`. */
|
||||
export function mutate(
|
||||
source: string,
|
||||
rng: Rng,
|
||||
ctx: MutationContext,
|
||||
mutators: readonly Mutator[] = MUTATORS,
|
||||
): { output: string; applied: string[] } {
|
||||
let output = source;
|
||||
const applied: string[] = [];
|
||||
const count = rng.int(1, 4);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const m = pickWeighted(rng, mutators);
|
||||
output = m.apply(output, rng, ctx);
|
||||
applied.push(m.id);
|
||||
}
|
||||
return { output, applied };
|
||||
}
|
||||
125
fuzz/src/normalize.ts
Normal file
125
fuzz/src/normalize.ts
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
import type { FormatterChanges } from "@gram-lang/format";
|
||||
|
||||
/**
|
||||
* Comparing two compilations "up to positions": the formatter moves text
|
||||
* around and canonicalizes spellings, while the meaning must not change.
|
||||
*
|
||||
* Every rule here is a deliberate, commented decision, each one checked
|
||||
* against the unmutated corpus. Never widen it to make a violation go away
|
||||
* without understanding it first: a difference is a formatter bug until a
|
||||
* rule below says it is a canonicalization.
|
||||
*/
|
||||
|
||||
/** Keys dropped wherever they appear. */
|
||||
export const POSITION_KEYS: ReadonlySet<string> = new Set([
|
||||
// Source location of AST nodes, copied onto usages and warnings.
|
||||
"loc",
|
||||
// Compiler name and version: not part of the recipe (same as
|
||||
// `withoutGenerator` in conformance/run.ts).
|
||||
"generator",
|
||||
// Source spelling of a quantity or timer (`180 °C`, `{1 cup+2 tbsp}`):
|
||||
// the formatter respaces it on purpose (rules 2-5); its parsed form
|
||||
// (`qty`, `unit`, `value`, durations) is still compared.
|
||||
"raw",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Formatter rules that *repair* a common mistake into the syntax the author
|
||||
* meant, so they change the compilation by design: `@a{} < @b{}` becomes a
|
||||
* composite (rule 6), `->&dough {}` a declaration (rule 7), `##Prep` a
|
||||
* section header instead of `#` + cookware `#Prep` (rule 8). I6 does not
|
||||
* compare an input on which one of them fired.
|
||||
*/
|
||||
export const MEANING_REPAIRS: readonly (keyof FormatterChanges)[] = [
|
||||
"compositeSeparatorSpacing",
|
||||
"arrowDeclarationSpacing",
|
||||
"headerSpacing",
|
||||
];
|
||||
|
||||
function normalizeText(text: string, isLast: boolean): string {
|
||||
// Rule 9 (tabs → 4 spaces) and rule 10 (trailing whitespace) rewrite prose.
|
||||
const out = text.replace(/\t/g, " ").replace(/[ \t]+(?=\r?\n)/g, "");
|
||||
return isLast ? out.replace(/[ \t]+$/, "") : out;
|
||||
}
|
||||
|
||||
export function normalize(value: unknown): unknown {
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v, i) =>
|
||||
typeof v === "string"
|
||||
? normalizeText(v, i === value.length - 1)
|
||||
: normalize(v),
|
||||
);
|
||||
}
|
||||
if (value && typeof value === "object") {
|
||||
const record = value as Record<string, unknown>;
|
||||
const out: Record<string, unknown> = {};
|
||||
for (const [key, v] of Object.entries(record)) {
|
||||
if (POSITION_KEYS.has(key)) continue;
|
||||
// A number's source spelling (`160.0`): rule 4 drops trailing
|
||||
// zeros; `value` holds the number itself.
|
||||
if (key === "text" && "value" in record) continue;
|
||||
// A warning's message quotes the source spelling (`"180 °C"`);
|
||||
// its `code` and the rest of its fields are still compared.
|
||||
if (key === "message" && "code" in record) continue;
|
||||
// Rule 1 lowercases ingredient ids (`@Farine` → `@farine`), and
|
||||
// the displayed name follows the source's case.
|
||||
if (key === "name" && typeof v === "string") {
|
||||
out[key] = v.toLowerCase();
|
||||
continue;
|
||||
}
|
||||
out[key] = normalize(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path of the first difference between two normalized values, or null
|
||||
* when they are equal. Paths look like `$.sections[0].steps[2].text`.
|
||||
*/
|
||||
export function firstDifference(
|
||||
a: unknown,
|
||||
b: unknown,
|
||||
path = "$",
|
||||
): string | null {
|
||||
if (Object.is(a, b)) return null;
|
||||
if (Array.isArray(a) && Array.isArray(b)) {
|
||||
const length = Math.max(a.length, b.length);
|
||||
for (let i = 0; i < length; i++) {
|
||||
const d = firstDifference(a[i], b[i], `${path}[${i}]`);
|
||||
if (d) return d;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
a &&
|
||||
b &&
|
||||
typeof a === "object" &&
|
||||
typeof b === "object" &&
|
||||
!Array.isArray(a) &&
|
||||
!Array.isArray(b)
|
||||
) {
|
||||
const ra = a as Record<string, unknown>;
|
||||
const rb = b as Record<string, unknown>;
|
||||
const keys = new Set([...Object.keys(ra), ...Object.keys(rb)]);
|
||||
for (const key of [...keys].sort()) {
|
||||
const d = firstDifference(ra[key], rb[key], `${path}.${key}`);
|
||||
if (d) return d;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* The coarse shape of a path, for signatures: indices blanked and only the
|
||||
* first segments kept (`$.sections[3].steps[0].text` → `$.sections[].steps[]`),
|
||||
* so one bug does not split into a signature per ingredient name or field.
|
||||
*/
|
||||
export function pathShape(path: string): string {
|
||||
const segments = path.replace(/\[\d+\]/g, "[]").split(".");
|
||||
// Frontmatter keys are the author's own words: stop at `$.meta`.
|
||||
const depth = segments[1] === "meta" ? 2 : 3;
|
||||
return segments.slice(0, depth).join(".");
|
||||
}
|
||||
89
fuzz/src/prepared.ts
Normal file
89
fuzz/src/prepared.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
import { analyze, type IngredientData } from "@gram-lang/analyzer";
|
||||
import { formatGram } from "@gram-lang/format";
|
||||
import { type CompilationResult, compile } from "@gram-lang/kitchen";
|
||||
import { getAST, type RecipeAST } from "@gram-lang/parser";
|
||||
|
||||
export type Outcome<T> =
|
||||
| { ok: true; value: T; ms: number }
|
||||
| { ok: false; error: unknown; ms: number };
|
||||
|
||||
function attempt<T>(fn: () => T): Outcome<T> {
|
||||
const start = performance.now();
|
||||
try {
|
||||
const value = fn();
|
||||
return { ok: true, value, ms: performance.now() - start };
|
||||
} catch (error) {
|
||||
return { ok: false, error, ms: performance.now() - start };
|
||||
}
|
||||
}
|
||||
|
||||
type Formatted = ReturnType<typeof formatGram>;
|
||||
|
||||
/**
|
||||
* Everything the invariants look at, computed once per input and only when
|
||||
* an invariant asks for it: the same string is never parsed twice.
|
||||
* A stage whose input stage failed is `null`.
|
||||
*/
|
||||
export class Prepared {
|
||||
readonly #cache = new Map<string, unknown>();
|
||||
|
||||
constructor(
|
||||
readonly source: string,
|
||||
readonly database: Record<string, IngredientData>,
|
||||
) {}
|
||||
|
||||
#memo<T>(key: string, fn: () => T): T {
|
||||
if (!this.#cache.has(key)) this.#cache.set(key, fn());
|
||||
return this.#cache.get(key) as T;
|
||||
}
|
||||
|
||||
get parse(): Outcome<RecipeAST> {
|
||||
return this.#memo("parse", () => attempt(() => getAST(this.source)));
|
||||
}
|
||||
|
||||
get compile(): Outcome<CompilationResult> | null {
|
||||
return this.#memo("compile", () => {
|
||||
const parsed = this.parse;
|
||||
return parsed.ok ? attempt(() => compile(parsed.value)) : null;
|
||||
});
|
||||
}
|
||||
|
||||
get analyze(): Outcome<unknown> | null {
|
||||
return this.#memo("analyze", () => {
|
||||
const compiled = this.compile;
|
||||
return compiled?.ok
|
||||
? attempt(() => analyze(compiled.value, this.database))
|
||||
: null;
|
||||
});
|
||||
}
|
||||
|
||||
get format(): Outcome<Formatted> {
|
||||
return this.#memo("format", () => attempt(() => formatGram(this.source)));
|
||||
}
|
||||
|
||||
/** `formatGram` run again on its own output. */
|
||||
get reformat(): Outcome<Formatted> | null {
|
||||
return this.#memo("reformat", () => {
|
||||
const formatted = this.format;
|
||||
return formatted.ok
|
||||
? attempt(() => formatGram(formatted.value.content))
|
||||
: null;
|
||||
});
|
||||
}
|
||||
|
||||
/** The formatted source, parsed then compiled. */
|
||||
get formattedCompile(): {
|
||||
parse: Outcome<RecipeAST>;
|
||||
compile: Outcome<CompilationResult> | null;
|
||||
} | null {
|
||||
return this.#memo("formattedCompile", () => {
|
||||
const formatted = this.format;
|
||||
if (!formatted.ok) return null;
|
||||
const parse = attempt(() => getAST(formatted.value.content));
|
||||
return {
|
||||
parse,
|
||||
compile: parse.ok ? attempt(() => compile(parse.value)) : null,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
56
fuzz/src/prng.ts
Normal file
56
fuzz/src/prng.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* A small seeded PRNG (sfc32, seeded through splitmix32), so a fuzz run is a
|
||||
* pure function of its seed: same seed, same inputs, on every machine.
|
||||
*/
|
||||
export interface Rng {
|
||||
/** Uniform float in [0, 1). */
|
||||
next(): number;
|
||||
/** Uniform integer in [min, max], both inclusive. */
|
||||
int(min: number, max: number): number;
|
||||
pick<T>(items: readonly T[]): T;
|
||||
chance(probability: number): boolean;
|
||||
}
|
||||
|
||||
function splitmix32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x9e3779b9) >>> 0;
|
||||
let z = state;
|
||||
z = Math.imul(z ^ (z >>> 16), 0x85ebca6b) >>> 0;
|
||||
z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35) >>> 0;
|
||||
return (z ^ (z >>> 16)) >>> 0;
|
||||
};
|
||||
}
|
||||
|
||||
export function createRng(seed: number): Rng {
|
||||
const init = splitmix32(seed);
|
||||
let a = init();
|
||||
let b = init();
|
||||
let c = init();
|
||||
let d = init();
|
||||
const u32 = (): number => {
|
||||
const t = (((a + b) >>> 0) + d) >>> 0;
|
||||
d = (d + 1) >>> 0;
|
||||
a = b ^ (b >>> 9);
|
||||
b = (c + (c << 3)) >>> 0;
|
||||
c = ((c << 21) | (c >>> 11)) >>> 0;
|
||||
c = (c + t) >>> 0;
|
||||
return t;
|
||||
};
|
||||
for (let i = 0; i < 12; i++) u32();
|
||||
const next = () => u32() / 0x100000000;
|
||||
return {
|
||||
next,
|
||||
int: (min, max) => min + Math.floor(next() * (max - min + 1)),
|
||||
pick: (items) => {
|
||||
if (items.length === 0) throw new Error("pick() from an empty list");
|
||||
return items[Math.floor(next() * items.length)] as (typeof items)[number];
|
||||
},
|
||||
chance: (probability) => next() < probability,
|
||||
};
|
||||
}
|
||||
|
||||
/** The seed of iteration `index` of a run: each iteration replays on its own. */
|
||||
export function iterationSeed(seed: number, index: number): number {
|
||||
return splitmix32((seed ^ Math.imul(index + 1, 0x27d4eb2d)) >>> 0)();
|
||||
}
|
||||
15
fuzz/src/regressions.ts
Normal file
15
fuzz/src/regressions.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { readdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** Minimized inputs of fixed bugs, replayed on every invariant at each run. */
|
||||
export const REGRESSIONS_DIR = join(import.meta.dir, "../regressions");
|
||||
|
||||
export function regressions(): { name: string; content: string }[] {
|
||||
return readdirSync(REGRESSIONS_DIR)
|
||||
.filter((f) => f.endsWith(".gram"))
|
||||
.sort()
|
||||
.map((name) => ({
|
||||
name,
|
||||
content: readFileSync(join(REGRESSIONS_DIR, name), "utf-8"),
|
||||
}));
|
||||
}
|
||||
114
fuzz/src/run.ts
Normal file
114
fuzz/src/run.ts
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
import type { IngredientData } from "@gram-lang/analyzer";
|
||||
import { exampleDatabase } from "./database";
|
||||
import { INVARIANTS, type Invariant, type Violation } from "./invariants";
|
||||
import { MUTATORS, type Mutator, mutate } from "./mutators";
|
||||
import { Prepared } from "./prepared";
|
||||
import { createRng, iterationSeed } from "./prng";
|
||||
|
||||
export interface CorpusEntry {
|
||||
id: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface GeneratedInput {
|
||||
index: number;
|
||||
corpusId: string;
|
||||
mutations: string[];
|
||||
input: string;
|
||||
}
|
||||
|
||||
export interface Finding extends Violation, GeneratedInput {
|
||||
/** How many inputs of the run hit this signature. */
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
seed: number;
|
||||
iterations: number;
|
||||
corpus: readonly CorpusEntry[];
|
||||
invariants?: readonly Invariant[];
|
||||
mutators?: readonly Mutator[];
|
||||
database?: Record<string, IngredientData>;
|
||||
/** Called after each input, e.g. for a progress line. */
|
||||
onInput?: (index: number) => void;
|
||||
}
|
||||
|
||||
/** Input `index` of a run: a pure function of (seed, index, corpus). */
|
||||
export function generateInput(
|
||||
seed: number,
|
||||
index: number,
|
||||
corpus: readonly CorpusEntry[],
|
||||
mutators: readonly Mutator[] = MUTATORS,
|
||||
): GeneratedInput {
|
||||
const rng = createRng(iterationSeed(seed, index));
|
||||
const base = rng.pick(corpus);
|
||||
const donors = corpus.map((c) => c.content);
|
||||
const { output, applied } = mutate(base.content, rng, { donors }, mutators);
|
||||
return { index, corpusId: base.id, mutations: applied, input: output };
|
||||
}
|
||||
|
||||
export function checkInput(
|
||||
input: string,
|
||||
invariants: readonly Invariant[] = INVARIANTS,
|
||||
database: Record<string, IngredientData> = exampleDatabase(),
|
||||
): Violation[] {
|
||||
const prepared = new Prepared(input, database);
|
||||
const out: Violation[] = [];
|
||||
for (const inv of invariants) {
|
||||
const v = inv.check(prepared);
|
||||
if (v) out.push(v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function collect(
|
||||
findings: Map<string, Finding>,
|
||||
violations: Violation[],
|
||||
generated: GeneratedInput,
|
||||
): void {
|
||||
for (const v of violations) {
|
||||
const existing = findings.get(v.signature);
|
||||
if (existing) existing.count++;
|
||||
else findings.set(v.signature, { ...v, ...generated, count: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Mutated inputs: one finding per signature, the first input that hit it. */
|
||||
export function runFuzz(opts: RunOptions): Finding[] {
|
||||
const invariants = opts.invariants ?? INVARIANTS;
|
||||
const database = opts.database ?? exampleDatabase();
|
||||
const findings = new Map<string, Finding>();
|
||||
for (let i = 0; i < opts.iterations; i++) {
|
||||
const generated = generateInput(opts.seed, i, opts.corpus, opts.mutators);
|
||||
collect(
|
||||
findings,
|
||||
checkInput(generated.input, invariants, database),
|
||||
generated,
|
||||
);
|
||||
opts.onInput?.(i);
|
||||
}
|
||||
return [...findings.values()];
|
||||
}
|
||||
|
||||
/** The corpus itself, unmutated (index -1, no mutation). */
|
||||
export function scanCorpus(
|
||||
corpus: readonly CorpusEntry[],
|
||||
invariants: readonly Invariant[] = INVARIANTS,
|
||||
database: Record<string, IngredientData> = exampleDatabase(),
|
||||
): Finding[] {
|
||||
const findings = new Map<string, Finding>();
|
||||
for (const entry of corpus) {
|
||||
const generated = {
|
||||
index: -1,
|
||||
corpusId: entry.id,
|
||||
mutations: [],
|
||||
input: entry.content,
|
||||
};
|
||||
collect(
|
||||
findings,
|
||||
checkInput(entry.content, invariants, database),
|
||||
generated,
|
||||
);
|
||||
}
|
||||
return [...findings.values()];
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue