Skip to content

Commit e0e51a5

Browse files
authored
docs(v4): cut the compile comments down to what they explain (#6449)
The comments added with `z.compile` had become an account of how each decision was reached β€” a setup sentence, the approach tried first, then the same point restated. The longest ran 1155 characters. Nothing over 300 remains in these three files. What each comment guards is kept: the issue numbers, the measured figures behind `stringLengthInCodePoints`, and the reason a construct is refused rather than compiled. Code is byte-identical β€” stripping every comment from both revisions leaves the three files unchanged. Follows the rule added in 463ebb3.
1 parent 6574e78 commit e0e51a5

3 files changed

Lines changed: 23 additions & 25 deletions

File tree

β€Žpackages/zod/src/compile.tsβ€Ž

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Side-effect-only module: enables AOT compilation for every schema constructed after this import. The only operation is installing a post-processor on `globalConfig`. Bundlers preserve this import because the file is listed in `package.json`'s `sideEffects` array; nothing else in `zod` references it, so apps that don't `import "zod/compile"` drop the entire compiler.
1+
// Side-effect-only: installs the post-processor on `globalConfig`. Listed in `package.json`'s `sideEffects`, and nothing else references it, so apps that never import it drop the compiler.
22
//
33
// Usage:
44
//
@@ -34,7 +34,7 @@ core.globalConfig.postProcessor = (inst: any) => {
3434
return originalRun(payload, ctx);
3535
}
3636
const compiled = compile(inst);
37-
// Only the run wrapper is installed. Copying the compiled parse/ safeParse closures here would make their INVALID fallback re-enter this instance's methods β€” which now route through the compiled run β€” executing user callbacks a third time on invalid input. The method β†’ wrapper path runs them exactly twice.
37+
// Only the run wrapper. Copying the compiled parse/safeParse closures would make their fallback re-enter this instance and run user callbacks a third time.
3838
inst._zod.run = compiled._zod.run;
3939
} catch {
4040
// Permanent fallback for unsupported schemas.

β€Žpackages/zod/src/v4/core/compile.tsβ€Ž

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ export function compile<T extends SomeType>(schema: T): T {
121121
return originalRun(payload, ctx);
122122
}
123123

124-
// The value is a placeholder the runtime memoizer is still filling in, so a reference cycle closes here. Only the runtime can finish it β€” and a transform on the cycle has to raise $ZodCyclicError from its own parse, which a compiled node would skip. Cheap to ask: no memo state on the ctx means no cycle in flight, which is every ordinary parse.
124+
// A memoized back-edge: only the runtime can close a reference cycle, and a transform on one must raise $ZodCyclicError from its own parse.
125125
if (ctx && isBackEdge(ctx, payload.value)) {
126126
return originalRun(payload, ctx);
127127
}
@@ -185,7 +185,7 @@ export function compileFastpass<T extends SomeType>(
185185
schema: T,
186186
options?: CompileFastpassOptions
187187
): CompiledFastpass<core.output<T>> {
188-
// A recursive schema can be re-entered by a single parse, which is how input containing a reference cycle terminates: the runtime memoizer registers each in-progress output before its children run, keyed on the parse context every schema in that call shares. The generated fast path takes an input and returns a value β€” it has no context to key on, so it would follow the cycle in the input until the stack ran out. Hand the whole schema to the runtime. Walking the graph reads `shape`, which some schemas define as a getter that throws (`z.pick()` with an unrecognized mask key). Treat "can't tell" as recursive: the runtime raises that error from the parse where it belongs, and every escape from here stays a ZodCompileUnsupportedError.
188+
// Cycle-breaking is keyed on the parse context, which generated code never receives. `shape` can be a getter that throws (z.pick() with an unrecognized mask key), so treat "can't tell" as recursive.
189189
let recursive = true;
190190
try {
191191
recursive = isRecursiveSchema(schema as any);
@@ -245,7 +245,7 @@ function newVar(ctx: CompileContext): string {
245245
return `v${ctx.varCounter++}`;
246246
}
247247

248-
// Runtime helper called from inside the compiled fast path. Black-boxes a child schema by running its `_zod.run` with a fresh payload. Returns either the parsed value, INVALID (validation failed, triggers outer fallback), or signals async-boundary-violation by returning INVALID when the run resolves asynchronously. Used by the runtime-island pattern (see `compileChild`).
248+
// Runs a child schema as a black box: its value, or INVALID for a failure or an async run.
249249
function runtimeRun(schema: SomeType, value: unknown): unknown {
250250
const result = (schema._zod.run as (p: ParsePayload, c: ParseContextInternal) => any)(
251251
{ value, issues: [] },
@@ -309,7 +309,7 @@ function generateChecks(doc: Doc, ctx: CompileContext, schema: SomeType, accesso
309309

310310
for (const check of schemaChecks) {
311311
const def = check._zod.def;
312-
// Custom `when` gates make the runtime skip a check conditionally; the fast path always runs it, which diverges (dangerously so for value-mutating checks). The six size/length classes auto-default `when` to "skip after aborting issues" β€” satisfied by the fast path's bail-on-first-failure, and they never mutate values, so they stay compilable.
312+
// A custom `when` skips a check the fast path always runs; the one auto-defaulted on size/length classes matches its bail-on-first-failure.
313313
if ((def as { when?: unknown }).when && !WHEN_DEFAULTED_CHECKS.has(def.check)) {
314314
throw new ZodCompileUnsupportedError(`check with a custom "when" condition`);
315315
}
@@ -740,7 +740,7 @@ function generateStringFormatCheck(doc: Doc, ctx: CompileContext, def: StringFor
740740
return accessor;
741741
}
742742

743-
// Formats whose `pattern` IS the entire check, so testing the regex is exact. A pattern is not on its own evidence of that: `credit_card` advertises a shape-only pattern and validates the Luhn digit separately, and `base64`, `ipv6` and friends do the same. Emitting the regex for one of those silently accepts invalid input, which is why this is an allowlist rather than an `if (def.pattern)` catch-all β€” an unrecognized format falls through to the throw below and takes the runtime path instead of a wrong fast one.
743+
// Formats whose `pattern` IS the whole check. An allowlist rather than `if (def.pattern)`, because credit_card, base64 and ipv6 carry a shape-only pattern and validate the rest separately.
744744
if (PATTERN_IS_COMPLETE.has(fmt) && def.pattern) {
745745
const patternConst = addConstant(ctx, def.pattern);
746746
doc.write(`${patternConst}.lastIndex = 0;`);
@@ -826,7 +826,7 @@ function generateCheck(doc: Doc, ctx: CompileContext, schema: SomeType, accessor
826826
const def = schema._zod.def;
827827
const type = def.type as SupportedSchemaType;
828828

829-
// Coercion is modelled nowhere: a coercing schema would compile to the bare type test and reject everything it was supposed to convert. Standalone the wrapper hides that, but inside a union a rejected branch is indistinguishable from one the runtime rejected, so a later branch wins and the parse silently returns a different value. Refuse at codegen time, which the union honours.
829+
// A coercing schema would compile to the bare type test and reject what it should convert; inside a union that reads as a rejected branch, so refuse at codegen.
830830
if ((def as { coerce?: boolean }).coerce) {
831831
throw new ZodCompileUnsupportedError(`coercion (z.coerce.${type}())`);
832832
}
@@ -966,7 +966,7 @@ function generateCheck(doc: Doc, ctx: CompileContext, schema: SomeType, accessor
966966
function generateStringCheck(doc: Doc, ctx: CompileContext, schema: SomeType, accessor: string): string {
967967
doc.write(`if (typeof ${accessor} !== "string") return INVALID;`);
968968

969-
// A string-format schema (z.email(), z.creditCard(), z.hostname(), …) carries its format on its own def rather than in def.checks, while z.string().email() puts it in def.checks. Both route through generateStringFormatCheck so the two can never drift: keeping a second copy of the format table here is what let z.creditCard() compile to its shape-only regex without the Luhn digit.
969+
// z.email() carries its format on the def, z.string().email() in def.checks; both route here so the format table has no second copy to drift from.
970970
const def = schema._zod.def as unknown as StringFormatDef & { format?: string };
971971
if (def.format === undefined) return accessor;
972972
return generateStringFormatCheck(doc, ctx, def, accessor);
@@ -1064,7 +1064,7 @@ function generateObjectCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
10641064
doc.write(`const ${inputVar} = ${accessor}[${util.esc(key)}];`);
10651065

10661066
if (propSchema._zod.optin !== undefined) {
1067-
// Any rung of the optin ladder means the container may omit this key. The runtime runs such properties even when absent, then ignores issues on absent keys only when the output is optional too. This is what makes exactOptional compositional: the child rejects explicit undefined, while the object layer suppresses that failure only for an actually absent key.
1067+
// Any optin rung means the key may be omitted. The runtime runs the property anyway and ignores issues only when the key is genuinely absent, which is what makes exactOptional compositional.
10681068
const outputVar = newVar(ctx);
10691069
doc.write(`let ${outputVar} = (() => {`);
10701070
doc.indented((d) => {
@@ -1103,7 +1103,7 @@ function generateObjectCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
11031103
const catchallType = catchall._zod.def.type;
11041104

11051105
if (catchallType === "never") {
1106-
// Strict object: reject unknown keys. Runtime iterates with for...in, so inherited enumerable keys count as unrecognized. An undeclared `__proto__` counts too (handleCatchall reports it before skipping the copy, see #6221) β€” it is only excluded from the *output*, never from this scan. A declared `__proto__` can't reach here; the shape key is rejected at compile time above. One `for...in` for every shape, which is what the runtime does. An own-key count is faster but only equivalent for a plain prototype, and guarding on the prototype meant rejecting a class instance whose own enumerable keys match β€” input the runtime accepts. Standalone the wrapper hid that; inside a union the branch merely looked rejected and a later one won, so the parse returned a different value with no error at all. `|| "true"` for an empty shape: with no keys the join is "" and the emitted `if () return INVALID;` is a syntax error, which the single top-level `new Function` rejects long after compileChild's per-branch catch could island it β€” so the whole tree lost its fast path. An empty strict object rejects any own enumerable key, which is what `true` says.
1106+
// Strict: one `for...in`, as the runtime does, so inherited enumerable keys count. An undeclared `__proto__` is reported here and excluded only from the output (#6221); an own-key count would wrongly reject a class instance.
11071107
const condition = keys.map((k) => `k !== ${util.esc(k)}`).join(" && ") || "true";
11081108
doc.write(`for (const k in ${accessor}) {`);
11091109
doc.indented((d) => {
@@ -1118,7 +1118,7 @@ function generateObjectCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
11181118
}
11191119
// else: strip mode (no catchall) - unknown keys ignored, only include known keys
11201120

1121-
// Build the output: shape keys first in declared order (the runtime assigns them before its catchall loop), then unknown keys in for...in order. Runtime inclusion rule (handlePropertyResult): a key on the middle rung is included iff the key is present on the input; otherwise iff its output value !== undefined OR the key is present. Props that can never output undefined keep the fast object-literal form.
1121+
// Shape keys in declared order, then unknown keys in for...in order. A middle-rung key is included iff present on the input, else iff its output is not undefined.
11221122
const outputVar = newVar(ctx);
11231123
const hasConditionalKeys = keys.some((k) => mayOutputUndefined(shape[k]!) || dropsWhenAbsent(shape[k]!));
11241124

@@ -1208,13 +1208,13 @@ function isExactOptional(schema: SomeType): boolean {
12081208
return (schema._zod as { traits?: Set<string> }).traits?.has("$ZodExactOptional") === true;
12091209
}
12101210

1211-
// A required object key whose value-level fast path would silently accept an absent key (which reads as `undefined`) needs an explicit `key in input` guard. Without it, schemas like `z.undefined()` / `z.any()` / unions containing undefined would pass for missing properties even though the runtime rejects them.
1211+
// A value-level fast path reads an absent key as `undefined`, so z.undefined(), z.any() and unions containing undefined would accept a missing property the runtime rejects.
12121212
function requiresPresenceCheck(schema: SomeType): boolean {
12131213
return schema._zod.optin === undefined && fastPathAcceptsAbsence(schema);
12141214
}
12151215

12161216
function fastPathAcceptsAbsence(schema: SomeType): boolean {
1217-
// A coercing schema materialises a value out of an absent key β€” `z.coerce.string()` turns one into "undefined" β€” but the runtime object refuses to let a coercion fill a key that was not there (#6405). Compilation refuses coercion, so the child becomes a runtime island, and an island is handed `input[key]` with no way to tell absent from explicitly undefined. Report it as absence-accepting so the object emits the presence guard that keeps the two apart.
1217+
// An island is handed `input[key]` and cannot tell absent from explicitly undefined, so report absence-accepting and let the object emit the presence guard (#6405).
12181218
if ((schema._zod.def as { coerce?: boolean }).coerce) return true;
12191219

12201220
const def = schema._zod.def as {
@@ -1414,7 +1414,7 @@ function generateLiteralCheck(doc: Doc, ctx: CompileContext, schema: SomeType, a
14141414

14151415
function generateEnumCheck(doc: Doc, ctx: CompileContext, schema: SomeType, accessor: string): string {
14161416
const values = (schema._zod as unknown as { values?: Set<unknown> }).values;
1417-
// `_zod.values` is cleared by z.partialRecord and similar helpers when they want a schema that *infers* like an enum but isn't structurally enumerated. Without a known value set the fast path can't check membership. Throw (rather than emit `return INVALID`) so containers island this child and unions fall back whole β€” a falsely-rejecting branch inside xor would otherwise corrupt the match count into a false accept.
1417+
// z.partialRecord and friends clear `_zod.values`, leaving no set to test membership against. Throw rather than emit INVALID so a union falls back whole instead of counting a false rejection.
14181418
if (!values) {
14191419
throw new ZodCompileUnsupportedError("enum schema without enumerated values");
14201420
}
@@ -1486,7 +1486,7 @@ function generateDefaultCheck(doc: Doc, ctx: CompileContext, schema: SomeType, a
14861486

14871487
function generateNonOptionalCheck(doc: Doc, ctx: CompileContext, schema: SomeType, accessor: string): string {
14881488
const def = schema._zod.def as unknown as { innerType: SomeType };
1489-
// The runtime inspects what the inner *produced*, not what it was given. Both directions matter: an inner catch or transform can turn a defined input into `undefined`, which has to be rejected, and an inner default turns an absent input into a value, which has to be accepted. Testing the input did neither.
1489+
// The runtime inspects what the inner produced, not what it was given: a catch can turn a defined input into undefined, a default an absent one into a value.
14901490
const innerOutput = generateCheck(doc, ctx, def.innerType, accessor);
14911491
const outputVar = newVar(ctx);
14921492
doc.write(`const ${outputVar} = ${innerOutput};`);
@@ -1748,7 +1748,7 @@ function generateRecordCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
17481748

17491749
doc.write(`const ${outputVar} = {};`);
17501750

1751-
// Exhaustive records: keyType has a known value set (enum/literal/etc.). Runtime validates every known key, applies key transforms to choose the output key, and rejects unrecognized string keys. Generate the same shape. The runtime gates this on `values && !def.partial`: z.partialRecord keeps its value set but every key is optional, so required-key codegen would reject a record missing one. A loose record passes an unrecognized key through rather than rejecting it, which the scan below cannot express either.
1751+
// Exhaustive record. The runtime gates this on `values && !def.partial`, since z.partialRecord keeps its value set but makes every key optional; a loose record passes unrecognized keys through, which the per-key scan cannot express.
17521752
const recordDef = def as unknown as { mode?: string; partial?: boolean };
17531753
const keyValues = recordDef.partial ? undefined : (def.keyType._zod as unknown as { values?: Set<unknown> }).values;
17541754
if (keyValues) {
@@ -1774,7 +1774,7 @@ function generateRecordCheck(doc: Doc, ctx: CompileContext, schema: SomeType, ac
17741774
doc.write(`${outputVar}[${outKey}] = ${valOutput};`);
17751775
}
17761776

1777-
// `mode: "loose"` only changes what happens to *unrecognized* keys β€” it still requires every enumerated key, so it belongs on this path rather than the per-present-key scan, which has no notion of a declared-but-absent key. Passing it through here matches the runtime, which copies the extra key across and skips `__proto__` so the assignment cannot reseat the output's prototype.
1777+
// `mode: "loose"` changes only what happens to unrecognized keys, so it belongs here rather than the per-present-key scan. Passing them through matches the runtime, which skips `__proto__`.
17781778
const knownKeysConst = addConstant(ctx, new Set(inputKeys));
17791779
doc.write(`for (const ${kVar} in ${accessor}) {`);
17801780
doc.indented((d) => {
@@ -2023,9 +2023,7 @@ function generateCatchCheck(doc: Doc, ctx: CompileContext, schema: SomeType, acc
20232023
catchValue: (ctx: any) => unknown;
20242024
};
20252025

2026-
// `.catch(value)` synthesises a tagged thunk for a constant, so anything untagged is a user callback. Every callback is refused, not just one that reads `ctx.error`: whether it does is undecidable here, and a callback that reads it needs issues finalized against the caller's per-parse error map, which generated code never sees. Producing them here gives a different message than `.parse(input, { error })` and, because catch *succeeds*, nothing downstream can notice. Refuse at codegen instead: returning INVALID would be a bail-out, and a union reads that as a rejected branch rather than a reason to hand the whole parse back.
2027-
//
2028-
// Not islandable either. A runtime island runs only this node through the runtime, and `runtimeRun` has no parse context to hand it, so an islanded catch finalizes against an empty context and *succeeds* with the wrong message β€” the same divergence, reintroduced by the container that was trying to tolerate it.
2026+
// An untagged catchValue is a user callback, and one reading `ctx.error` needs the caller's per-parse error map. Catch *succeeds*, so a wrong message there is unobservable β€” refuse at codegen, and not islandable either, since `runtimeRun` has no context to hand it.
20292027
if (!(def.catchValue as { [util.CONSTANT_CATCH]?: boolean })[util.CONSTANT_CATCH]) {
20302028
throw new ZodCompileUnsupportedError("catch with a callback (only a constant catch value compiles)", false);
20312029
}

0 commit comments

Comments
Β (0)