Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .claude/skills/benchmark/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,10 @@ runs in both, so its two results show how much the machine moved. Heavy runs go
took 6 h 17 min (run 41364890698); a filter of 13 cases at 12 rounds took 2 hours (41399172268).
- **Skip an A/B whose code is unchanged** (identical generated files or machine code prove it), and prove it per
runtime before requesting the line: Go, `go test -c` the bench at both commits and diff `go tool objdump` with
paths and addresses stripped; TypeScript, runtime-ab runs the head's `bench.ts` on both sides, so the sides differ
only in `src/nino.ts`, what nino-gen writes for `bench/Bench.dll` and the data `Bench.dll` writes (diff all
three); Rust, `objdump -d` the bench binary each side builds with the line's
paths and addresses stripped; in TypeScript, diff each revision's benchmark harness, `src/nino.ts`, and the
codecs and data its `bench/generate.sh` writes. Since #374 the runtime A/B workflow runs each revision's own
harness and generates its fixtures from the .NET benchmark schema. In Rust, run `objdump -d` on each benchmark
binary built with the line's
`RUSTFLAGS=-Cllvm-args=-align-all-functions=6`, addresses stripped (after items moved between modules, also
the `::h<hash>` suffixes, the moved paths mapped and the `# <symbol>` comments; criterion's code and a bench's
own setup can land in other codegen units of the bench crate, so compare every `nino::` function and timed
Expand Down
7 changes: 7 additions & 0 deletions .claude/skills/optimize-runtimes/references/inlining-gc.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ Read it before growing a TypeScript or Rust hot helper, or when a TypeScript cas
when a shape helps one target and hurts another, put it behind `cfg(target_arch)` and keep the generic loop for
every other target (the map read taking one check per entry is x86/x86_64 only: on Arm64 it held the key/value pair
in a SIMD register across the hash call and Neoverse-N2 ran 3 to 4 % slower). Test both paths (`platforms`).
- Flatten the TypeScript runtime modules into one lexical scope for npm and nino-gen. On Node 22.23.4, #247's
single-file output kept the bytecode lengths and TurboFan inlining of the monolith's string and Latin-1 paths,
numeric blocks, and generated IntArray, BoolArray and ByteArray readers, both with and without `Buffer`.
Compare `--print-bytecode` lengths and `--trace-turbo-inlining` call edges after warming both paths of each build.
The MixedStrings runner A/B and same-revision controls (44329792122) put the modular bundle within 5 %
by per-CPU median on every measured x64 CPU and Neoverse-N2. On Neoverse-N2 the medians moved −1.13 % for
serialize, −1.17 % for serializeInto and −0.11 % for deserialize.
- TypeScript output is the bytes it writes: a slower serialize in a large heap is often GC, not the loop. Before changing
a write loop for a case that got slower, run it with `--trace-gc` and read whose pauses land in its task. Every new
`ArrayBuffer` counts as external memory, and Node 24 starts a full GC for each 64 MB of them that no scavenge
Expand Down
2 changes: 2 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ runtimes/rust/tests/conformance/types.rs linguist-generated
runtimes/go/internal/generated/**/nino_types.go linguist-generated
runtimes/rust/tests/generated/*.rs linguist-generated
runtimes/typescript/test/generated/*.ts linguist-generated
# npm run build:bundle
runtimes/typescript/src/nino.ts linguist-generated
# Protocol Buffers code the runtimes' benchmarks compare against.
*.pb.go linguist-generated
*_pb.ts linguist-generated
Expand Down
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ one (CI runs `tools/agents.sh --check`, which also checks that every file is in
| [`runtimes/csharp/tests/`](runtimes/csharp/tests/AGENTS.md) | adding or changing a test, or finding where a feature, a platform or hostile input is tested |
| [`runtimes/go/`](runtimes/go/AGENTS.md) | reading or changing the Go runtime (runtimes/go, package nino), its string kernels, struct tags, sample codecs or Go benchmark |
| [`runtimes/rust/`](runtimes/rust/AGENTS.md) | reading or changing the Rust runtime (runtimes/rust: crates nino-serialization and nino-serialization-derive), its SIMD kernels, tests or benchmarks |
| [`runtimes/typescript/`](runtimes/typescript/AGENTS.md) | reading or changing the TypeScript runtime (runtimes/typescript: src/nino.ts, its WebAssembly kernels, tests or benchmark) |
| [`runtimes/typescript/`](runtimes/typescript/AGENTS.md) | reading or changing the TypeScript runtime (runtimes/typescript: src/runtime/, its single-file bundle, WebAssembly kernels, tests or benchmark) |
| [`tests/conformance/`](tests/conformance/AGENTS.md) | changing the wire format, a layout, a malicious-input check or a sample type, or making a runtime read the shared conformance corpus |
<!-- agents-index:end -->

Expand Down
9 changes: 5 additions & 4 deletions docs/codegen.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,12 @@ directory, deleting what the list names but this run no longer writes.

The generated API of each language is on the site; these are the decisions behind it.

- **TypeScript** (`TypeScriptTarget`): the module of an assembly, with `nino.ts` (embedded in the tool from
`runtimes/typescript/src/nino.ts`) written next to it unless `--runtime` names a module. The bodies of types without
members (`readBody$Empty`, `writeBody$Empty` and the version-tolerant ones) name their parameters `_r`, `_w` and
- **TypeScript** (`TypeScriptTarget`): the module of an assembly, with the embedded runtime bundle (`runtimes/typescript/src/nino.ts`)
written next to it unless `--runtime` names a module. The bodies of types without members (`readBody$Empty`, `writeBody$Empty` and the version-tolerant ones) name their parameters `_r`, `_w` and
`_v`, so the code compiles under `noUnusedParameters`. With `--numeric-arrays typed`,
`TypeScriptTarget.NumberArrays` chooses the typed array of each fixed-size number.
`TypeScriptTarget.NumberArrays` chooses the typed array of each fixed-size number. Rectangular arrays of rank
2 to 4 have a `NinoGrid<TData>` shape with `lengths` and flat row-major `data`. Numeric grids use typed storage
in either mode, and grids of raw nullable elements use `NullableSlot<T>[]`.
- **Go** (`GoTarget`): read and write functions in the shape of the hand-written codecs in
`runtimes/go/internal/sample`: one `Take`/`Extend` per run of fixed-size members, no reflection, and a direct call
for each class body and each element of a collection (no function values; `optimize-runtimes`).
Expand Down
3 changes: 2 additions & 1 deletion runtimes/csharp/src/Nino.Codegen/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ dotnet tool `Nino.Codegen.Tool`. `audit-runtimes` audits it, `audit-generated-co

```
Nino.Codegen.csproj the exe (nino-gen.dll, no apphost) and the package: tools/ holds it and its assemblies,
build/ the targets; embeds Templates/**/*.sbn and runtimes/typescript/src/nino.ts
build/ the targets; embeds Templates/**/*.sbn and the single-file TypeScript bundle
runtimes/typescript/src/nino.ts (see runtimes/typescript/AGENTS.md)
Program.cs the command line: --assembly <dll> --lang ts|go|rust --out <dir> [options]; writes a file
only when its text changes, and deletes what its manifest (.nino-gen) lists but this run
no longer writes
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace Nino.Codegen.Targets
/// <summary>
/// How a value is written in TypeScript (<see cref="Kind"/>: <c>prim</c>, <c>enum</c>, <c>rawstruct</c>,
/// <c>rawnullable</c>, <c>fixedtuple</c>, <c>tuple</c>, <c>string</c>, <c>utf8</c>, <c>object</c>,
/// <c>nullable</c>, <c>bytes</c>, <c>seq</c>, <c>map</c>, <c>type</c>, <c>param</c>: a type parameter,
/// <c>nullable</c>, <c>bytes</c>, <c>seq</c>, <c>map</c>, <c>grid</c>, <c>type</c>, <c>param</c>: a type parameter,
/// <c>generic</c>: a generic type with its arguments in <see cref="Items"/>): the template turns it into a type, a
/// default, and code reading and writing it, alone or at an offset.
/// </summary>
Expand Down Expand Up @@ -64,6 +64,9 @@ public sealed class TsShape
/// <summary>A set (<c>Set</c>) rather than an array.</summary>
public bool Set { get; internal set; }

/// <summary>The number of dimensions of a rectangular array.</summary>
public int Rank { get; internal set; }

/// <summary>
/// How a set's element or a map's key of this shape passes through <c>NinoKeyGuard</c> (the runtime's bound on
/// hash flooding for the keys V8 hashes without a seed): <c>int</c> (an int32 value), <c>number</c>,
Expand Down Expand Up @@ -144,7 +147,7 @@ private IEnumerable<string> Parts()
yield return Struct?.FullName ?? "";
yield return Type?.FullName ?? "";
yield return Header ?? "";
yield return Set ? "set" : "";
yield return Set ? "set" : Rank == 0 ? "" : Rank.ToString(System.Globalization.CultureInfo.InvariantCulture);
yield return ArrayType ?? "";
yield return FlagOffset + "/" + ValueOffset + (Clean ? "/clean" : "");
yield return string.Join("/", Offsets);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,21 @@ internal TsShape Shape(ValueModel value)
var (key, mapValue) = (Shape(value.Key!), Shape(value.Value!));
return InContext(value, Holding(new TsShape("map") { Key = key, Value = mapValue }, key, mapValue));
}
case ValueKind.Grid:
{
if (value.Rank is < 2 or > 4)
throw new UnsupportedException($"{value.ClrName} has unsupported array rank {value.Rank}");
var element = Shape(value.Element!);
element.SlotElement = element is { Kind: "rawnullable", Clean: false };
string? array = null;
if (element.Kind == "prim")
NumberArrays.TryGetValue(element.Primitive!, out array);
return InContext(value, Holding(new TsShape("grid")
{
Element = element, Rank = value.Rank, ArrayType = array,
InlineLength = array == null ? 0 : 64 / element.Size,
}, element));
}
case ValueKind.Tuple:
{
// The items one after another: at fixed offsets when they all have a fixed size.
Expand All @@ -215,7 +230,7 @@ internal TsShape Shape(ValueModel value)
case ValueKind.Unsupported:
throw new UnsupportedException(Problem(value));
default:
// grid, bigint, version, datetimeoffset.
// bigint, version, datetimeoffset.
throw new UnsupportedException($"{value.ClrName} ({KindName(value)}) has no TypeScript form");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ public string Render(string source)
aliases.Add(alias);
return alias + "<" + inner + ">";
}));
renderer.Function("grid_type", new Func<string, string>(data =>
{
// A .NET type may also be named NinoGrid. Its generated name never contains a dollar sign.
aliases.Add("NinoGrid as NinoGrid$");
return "NinoGrid$<" + data + ">";
}));
string text = renderer.Render("types.sbn").TrimEnd('\n') + "\n";
return text.Replace(MoreImports, string.Concat(aliases.Select(a => ", type " + a)));
}
Expand Down Expand Up @@ -295,13 +301,15 @@ internal List<TsMember> Members(TypeModel type)
/// </summary>
private string Helper(TsShape shape, string mode)
{
if (mode == "readinto" && (shape.Kind == "grid" || shape.ArrayType != null))
mode = "read";
string key = mode + ":" + shape.Identity;
if (_helperByKey.TryGetValue(key, out var helper))
return helper.Name;
// The functions the value's code calls come first.
switch (shape.Kind)
{
case "seq" when !shape.Element!.Fixed:
case "seq" or "grid" when !shape.Element!.Fixed:
Touch(shape.Element, mode);
break;
case "map" when !(shape.Key!.Fixed && shape.Value!.Fixed):
Expand Down Expand Up @@ -334,6 +342,7 @@ private void Touch(TsShape shape, string mode)
{
case "seq":
case "map":
case "grid":
case "rawnullable":
case "fixedtuple":
Helper(shape, mode);
Expand Down
15 changes: 13 additions & 2 deletions runtimes/csharp/src/Nino.Codegen/Templates/typescript/shapes.sbn
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ func map_ts(s)
ret "Map<" + ts(s.key) + ", " + ts(s.value) + ">"
end

func grid_ts(s)
ret grid_type(seq_ts(s))
end

func ts(s)
case s.kind
when "prim"
Expand Down Expand Up @@ -109,6 +113,8 @@ func ts(s)
ret seq_ts(s) + " | null"
when "map"
ret map_ts(s) + " | null"
when "grid"
ret grid_ts(s) + " | null"
when "type"
if s.header == "typeid" || s.header == "ref" || s.header == "union"
ret name(s.type) + " | null"
Expand Down Expand Up @@ -226,7 +232,7 @@ func read(s)
ret read(s.inner) + " as " + name(s.enum)
when "rawstruct"
ret "read" + name(s.struct) + "(r, r.take(" + s.size + "))"
when "rawnullable", "fixedtuple", "seq", "map"
when "rawnullable", "fixedtuple", "seq", "map", "grid"
ret helper(s, "read") + "(r" + s.codecs_argument + ")"
when "tuple"
$parts = []
Expand Down Expand Up @@ -263,6 +269,11 @@ end
# none): the objects, arrays, maps and sets it holds are reused where they can be (`deserializeInto`), else a new value.
func read_into(s, cur)
case s.kind
when "grid"
if s.array_type
ret read(s)
end
ret helper(s, "read") + "(r" + s.codecs_argument + ", " + cur + ")"
when "seq", "map"
if s.array_type
ret read(s)
Expand Down Expand Up @@ -305,7 +316,7 @@ func write(s, v)
ret write(s.inner, v)
when "rawstruct"
ret "write" + name(s.struct) + "(w, " + reserve(s.size, s.zeroed) + ", " + v + ")"
when "rawnullable", "fixedtuple", "seq", "map"
when "rawnullable", "fixedtuple", "seq", "map", "grid"
ret helper(s, "write") + "(w, " + v + s.codecs_argument + ")"
when "tuple"
$parts = []
Expand Down
42 changes: 42 additions & 0 deletions runtimes/csharp/src/Nino.Codegen/Templates/typescript/types.sbn
Original file line number Diff line number Diff line change
Expand Up @@ -360,9 +360,51 @@ func guard_decl(shape)
ret shape.guard ? " const guard = r.keyGuard(length);\n" : ""
end

# The grid dimensions take the place of a sequence's count. The elements follow with the same stride.
func grid_helper(h)
$s = h.shape
$t = grid_ts($s)
$e = $s.element
if h.mode == "read"
$reuse = !$s.array_type ? ", cur?: " + $t + " | null" : ""
$min = $e.fixed ? $e.size : 1
$o = "function " + h.name + h.type_params + "(r: NinoReader" + h.codecs + $reuse + "): " + $t + " | null {\n const shape = r.gridShape(" + $s.rank + ", " + $min + ");\n if (shape === null) return null;\n const { lengths, count } = shape;\n"
if $s.array_type
$o = $o + " if (count > " + $s.inline_length + ") return { lengths, data: r.numbers(" + $s.array_type + ", count)! };\n"
$o = $o + " const values = new " + $s.array_type + "(count);\n"
else
$o = $o + " const reuse = cur != null && lengths.length === cur.lengths.length && lengths.every((n, i) => n === cur.lengths[i]);\n const values = reuse ? cur.data : new Array<" + ts($e) + ">(r.capacity(count));\n"
end
if $e.fixed
$o = $o + " for (let i = 0, at = r.take(count * " + $e.size + "); i < count; i++, at += " + $e.size + ") values[i] = " + read_at($e, 0) + ";\n"
else
$o = $o + " for (let i = 0; i < count; i++) values[i] = " + read_into($e, "values[i]") + ";\n"
end
if !$s.array_type
$o = $o + " if (values.length !== count) values.length = count;\n if (reuse) return cur;\n"
end
ret $o + " return { lengths, data: values };\n}\n"
end

$o = "function " + h.name + h.type_params + "(w: NinoWriter, grid: " + $t + " | null" + h.codecs + "): void {\n if (grid == null) { w.i32(-1); return; }\n const values = grid.data;\n w.gridShape(" + $s.rank + ", grid.lengths, values.length);\n"
if $s.array_type
$o = $o + " if (values.length > " + $s.inline_length + ") { w.numberBlock(values); return; }\n"
end
$loop = " for (let i = 0; i < values.length; i++) {\n const value = values[i];\n"
if $e.fixed
$o = $o + " let at = " + reserve("values.length * " + $e.size, $e.zeroed) + ";\n" + $loop + " " + stmt(write_at($e, 0, "value")) + "\n at += " + $e.size + ";\n }\n"
else
$o = $o + $loop + " " + stmt(write($e, "value")) + "\n }\n"
end
ret $o + "}\n"
end

# A function shared by every value of one shape.
func helper_body(h)
$s = h.shape
if $s.kind == "grid"
ret grid_helper(h)
end
$n = h.name
$o = ""
if h.mode == "readinto"
Expand Down
2 changes: 1 addition & 1 deletion runtimes/csharp/tests/Nino.Codegen.Tests/Shapes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ public sealed class NullableSlots
public List<(int, int?)> Tuples;
}

/// <summary>Raw nullables as the elements of arrays of two and three dimensions: slots too (TypeScript has no grids).</summary>
/// <summary>Raw nullables as the elements of arrays of two and three dimensions: slots too.</summary>
[NinoType]
public sealed class NullableGrids
{
Expand Down
6 changes: 4 additions & 2 deletions runtimes/csharp/tests/Nino.Codegen.Tests/TargetTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -275,11 +275,13 @@ public void RawNullableSlotsAreGeneratedInEveryLanguage()
StringAssert.Contains(ts, " sorted: Set<NullableSlot<number>> | null = null;");
StringAssert.Contains(ts, " boxedNested: Box<(Set<NullableSlot<bigint>> | null)[] | null> | null = null;");
StringAssert.Contains(ts, " tuples: ([number, number | null])[] | null = null;");
StringAssert.Contains(ts, "import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoNullable, type NullableSlot } from");
StringAssert.Contains(ts, "import { NinoReader, NinoSubtypes, NinoWriter, type NinoCodec, type NinoGrid as NinoGrid$, type NinoNullable, type NullableSlot } from");
StringAssert.Contains(ts, " map: Map<number, bigint | null> | null = null;");
// A set's slots are taken as one run, then each read at its offset.
StringAssert.Contains(ts, "for (let i = 0, at = r.take(length * 8); i < length; i++, at += 8) values.add(");
StringAssert.Contains(tsOutput, "Shapes.NullableGrids is not written to TypeScript");
StringAssert.Contains(ts, " grid: NinoGrid$<NullableSlot<number>[]> | null = null;");
StringAssert.Contains(ts, " cube: NinoGrid$<NullableSlot<bigint>[]> | null = null;");
Assert.IsFalse(tsOutput.Contains("NullableGrids", StringComparison.Ordinal), tsOutput);
var (go, goOutput) = Run("go", "nino_types.go");
Assert.IsTrue(Regex.IsMatch(go, @"\n\tQueue +\[\]nino\.NullableSlot\[int32\] "));
Assert.IsTrue(Regex.IsMatch(go, @"\n\tSorted +\[\]nino\.NullableSlot\[int32\] "));
Expand Down
Loading
Loading