feat(proton): add @snowluma/proton — compile-time protobuf DSL
Vendors SnowLuma/protobuf-dsl into the monorepo as @snowluma/proton, with
edge-case fixes applied on top of the upstream source. Reference copy of
the unmodified upstream is kept under dev/protobuf-dsl/.
Edge cases fixed (each with a regression test):
- Aliased pb / pb_repeated marker imports (`import { pb as P }`)
— collector now resolves the marker name through the import resolver
- Concrete interface with a generic-instantiated message field
(`wrapped: pb<5, Wrapper<uint_32>>`) — field typeName now resolves
to the mangled form, and the inner instantiation is queued for
monomorphization
- Generic template with a generic-instantiated field
(`interface Outer<U> { x: pb<5, Wrapper<U>> }`) — the inner
instantiation is now re-substituted and re-monomorphized at outer
instantiation time
- Wrapper-binding synthetic SourceFile was empty-text — getText()
returned garbage, breaking mangled name computation downstream
- Cross-file forwarded wrappers (chain → imported base) were not
detected — parseFileForDefinitions now resolves imports recursively
(value imports only, with cycle protection)
- matchForwardedKnownWrapper did not propagate typePattern — chain
treated <X> as the encoded type instead of Wrapper<X>
- Synthetic-SF WeakMap was private to analyzer.ts — replacer could
not see it. Moved to utils.ts so typeNodeToMangledName picks it up
automatically.
Defensive guard: any field whose typeName resolves to neither a primitive
nor a known message now throws at analyze() time, instead of silently
leaking the WireType.Varint placeholder into codegen.
95/95 tests pass; tsc --noEmit clean.
This commit is contained in:
62 files changed
+4714
No files matched your search
@@ -0,0 +1,154 @@
|
||||
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
|
||||
|
||||
function tagValue(field: ProtobufField): number {
|
||||
const wireType = field.isMessage || field.typeName === 'string' || field.typeName === 'bytes'
|
||||
? WireType.LengthDelim
|
||||
: field.wireType;
|
||||
return ((field.fieldNumber << 3) | wireType) >>> 0;
|
||||
}
|
||||
|
||||
/** Emit inline varint decode, storing result in `varName`. */
|
||||
function varintDec(varName: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let ${varName} = data[offset++];`,
|
||||
`${ind}if (${varName} & 0x80) {`,
|
||||
`${ind} let _s = 7, _b;`,
|
||||
`${ind} ${varName} &= 0x7f;`,
|
||||
`${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`,
|
||||
`${ind}}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function varintDec64(varName: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let ${varName} = 0n, _s = 0n, _b;`,
|
||||
`${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function isVarint64(typeName: string): boolean {
|
||||
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
|
||||
}
|
||||
|
||||
function isFixed64BigInt(typeName: string): boolean {
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
}
|
||||
|
||||
const INLINE_SKIP = [
|
||||
` const wireType = _tag & 0x7;`,
|
||||
` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`,
|
||||
` else if (wireType === 1) offset += 8;`,
|
||||
` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`,
|
||||
` else if (wireType === 5) offset += 4;`,
|
||||
].join('\n');
|
||||
|
||||
export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
|
||||
const locals = msg.fields.map((field, index) => {
|
||||
const keyword = field.isRepeated ? 'const' : 'let';
|
||||
return ` ${keyword} _f${index} = ${getDefault(field)};`;
|
||||
});
|
||||
const result = msg.fields.map((field, index) => `${field.name}: _f${index}`).join(', ');
|
||||
|
||||
const L = [
|
||||
`function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`,
|
||||
...locals,
|
||||
` while (offset < end) {`,
|
||||
` let _tag = data[offset++];`,
|
||||
` if (_tag & 0x80) {`,
|
||||
` let _ts = 7, _tb;`,
|
||||
` _tag &= 0x7f;`,
|
||||
` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`,
|
||||
` }`,
|
||||
` switch (_tag) {`,
|
||||
];
|
||||
|
||||
msg.fields.forEach((field, index) => {
|
||||
L.push(decodeField(field, index));
|
||||
});
|
||||
|
||||
L.push(
|
||||
` default: {`,
|
||||
INLINE_SKIP,
|
||||
` break;`,
|
||||
` }`,
|
||||
` }`,
|
||||
` }`,
|
||||
` return { ${result} };`,
|
||||
`}`,
|
||||
);
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
function decodeField(field: ProtobufField, index: number): string {
|
||||
const { typeName, wireType, isMessage, isRepeated } = field;
|
||||
const I = ' ';
|
||||
const local = `_f${index}`;
|
||||
const assign = (expr: string) => isRepeated
|
||||
? `${I}${local}.push(${expr});`
|
||||
: `${I}${local} = ${expr};`;
|
||||
|
||||
const L: string[] = [` case ${tagValue(field)}: {`];
|
||||
|
||||
if (isMessage) {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`));
|
||||
L.push(`${I}offset += _len;`);
|
||||
} else if (typeName === 'string') {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(`${I}const _end = offset + _len;`);
|
||||
L.push(assign(`__td.decode(data.subarray(offset, _end))`));
|
||||
L.push(`${I}offset = _end;`);
|
||||
} else if (typeName === 'bytes') {
|
||||
L.push(varintDec('_len', I));
|
||||
L.push(`${I}const _end = offset + _len;`);
|
||||
L.push(assign(`data.slice(offset, _end)`));
|
||||
L.push(`${I}offset = _end;`);
|
||||
} else if (typeName === 'bool') {
|
||||
L.push(varintDec('_val', I));
|
||||
L.push(assign(`_val !== 0`));
|
||||
} else if (isVarint64(typeName)) {
|
||||
L.push(varintDec64('_val', I));
|
||||
if (typeName === 'uint_64') {
|
||||
L.push(assign(`_val`));
|
||||
} else if (typeName === 'int_64') {
|
||||
L.push(assign(`BigInt.asIntN(64, _val)`));
|
||||
} else {
|
||||
L.push(assign(`__zigZagDecode64(_val)`));
|
||||
}
|
||||
} else if (typeName === 'sint_32') {
|
||||
L.push(varintDec('_val', I));
|
||||
L.push(assign(`(_val >>> 1) ^ -(_val & 1)`));
|
||||
} else if (wireType === WireType.Varint) {
|
||||
L.push(varintDec('_val', I));
|
||||
L.push(assign(`_val >>> 0`));
|
||||
} else if (typeName === 'float') {
|
||||
L.push(assign(`__readFloat32(data, offset)`));
|
||||
L.push(`${I}offset += 4;`);
|
||||
} else if (wireType === WireType.Bit32) {
|
||||
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
|
||||
L.push(`${I}offset += 4;`);
|
||||
} else if (typeName === 'double') {
|
||||
L.push(assign(`__readFloat64(data, offset)`));
|
||||
L.push(`${I}offset += 8;`);
|
||||
} else if (isFixed64BigInt(typeName)) {
|
||||
if (typeName === 'fixed_64') {
|
||||
L.push(assign(`__readFixed64(data, offset)`));
|
||||
} else {
|
||||
L.push(assign(`BigInt.asIntN(64, __readFixed64(data, offset))`));
|
||||
}
|
||||
L.push(`${I}offset += 8;`);
|
||||
} else if (wireType === WireType.Bit64) {
|
||||
L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`));
|
||||
L.push(`${I}offset += 8;`);
|
||||
}
|
||||
|
||||
L.push(`${I}break;`, ` }`);
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
function getDefault(field: ProtobufField): string {
|
||||
if (field.isRepeated) return '[]';
|
||||
if (field.isOptional || field.isMessage) return 'null';
|
||||
const primitive = PRIMITIVE_TYPE_MAP[field.typeName];
|
||||
return primitive ? primitive.defaultValue : 'null';
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
import { WireType, type ProtobufField, type ProtobufMessage, type MessageRegistry } from '../ast/types.js';
|
||||
|
||||
/**
|
||||
* Pre-compute tag bytes at codegen time.
|
||||
* Field 1 + Varint(0) -> [0x08], Field 1 + LenDelim(2) -> [0x0a], etc.
|
||||
*/
|
||||
function computeTagBytes(fieldNumber: number, wireType: number): number[] {
|
||||
let value = ((fieldNumber << 3) | wireType) >>> 0;
|
||||
const bytes: number[] = [];
|
||||
while (value > 0x7f) {
|
||||
bytes.push((value & 0x7f) | 0x80);
|
||||
value >>>= 7;
|
||||
}
|
||||
bytes.push(value & 0x7f);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function writeTag(fieldNumber: number, wireType: number, ind: string): string {
|
||||
return computeTagBytes(fieldNumber, wireType)
|
||||
.map(byte => `${ind}buf[offset++] = ${byte};`)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function varintSize(varName: string, ind: string): string {
|
||||
return `${ind}size += ${varName} < 0x80 ? 1 : ${varName} < 0x4000 ? 2 : ${varName} < 0x200000 ? 3 : ${varName} < 0x10000000 ? 4 : 5;`;
|
||||
}
|
||||
|
||||
function writeVarint(expr: string, ind: string): string {
|
||||
return [
|
||||
`${ind}let _v = ${expr};`,
|
||||
`${ind}if (_v < 0x80) {`,
|
||||
`${ind} buf[offset++] = _v;`,
|
||||
`${ind}} else if (_v < 0x4000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 7;`,
|
||||
`${ind}} else if (_v < 0x200000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 14;`,
|
||||
`${ind}} else if (_v < 0x10000000) {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 21;`,
|
||||
`${ind}} else {`,
|
||||
`${ind} buf[offset++] = (_v & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 7) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 14) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = ((_v >>> 21) & 0x7f) | 0x80;`,
|
||||
`${ind} buf[offset++] = _v >>> 28;`,
|
||||
`${ind}}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function isVarint64(typeName: string): boolean {
|
||||
return typeName === 'uint_64' || typeName === 'int_64' || typeName === 'sint_64';
|
||||
}
|
||||
|
||||
function isFixed64BigInt(typeName: string): boolean {
|
||||
return typeName === 'fixed_64' || typeName === 'sfixed_64';
|
||||
}
|
||||
|
||||
function bigintVarintExpr(typeName: string, expr: string): string {
|
||||
if (typeName === 'uint_64') return `BigInt.asUintN(64, ${expr})`;
|
||||
if (typeName === 'int_64') return `BigInt.asUintN(64, ${expr})`;
|
||||
return `__zigZagEncode64(${expr})`;
|
||||
}
|
||||
|
||||
interface EncoderBlock {
|
||||
declare: string[];
|
||||
size: string[];
|
||||
write: string[];
|
||||
}
|
||||
|
||||
export function generateEncoder(msg: ProtobufMessage, _registry: MessageRegistry): string {
|
||||
const blocks = msg.fields.map((field, index) => field.isRepeated ? buildRepeatedBlock(field, index) : buildSingularBlock(field, index));
|
||||
|
||||
const L = [
|
||||
`function protobuf_encode_${msg.name}(obj) {`,
|
||||
` let size = 0;`,
|
||||
...blocks.flatMap(block => block.declare),
|
||||
...blocks.flatMap(block => block.size),
|
||||
` const buf = new Uint8Array(size);`,
|
||||
` let offset = 0;`,
|
||||
...blocks.flatMap(block => block.write),
|
||||
` return buf;`,
|
||||
`}`,
|
||||
];
|
||||
return L.join('\n');
|
||||
}
|
||||
|
||||
function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const valueVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length;
|
||||
|
||||
if (isMessage) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${valueVar} != null) {`,
|
||||
` ${cacheVar} = protobuf_encode_${typeName}(${valueVar});`,
|
||||
` const _len = ${cacheVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null) {`,
|
||||
` const _data = ${cacheVar};`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== "") {`,
|
||||
` ${cacheVar} = __utf8Len(${valueVar});`,
|
||||
` const _len = ${cacheVar};`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== "") {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${cacheVar};`,
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
|
||||
` const _len = ${valueVar}.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar}.length > 0) {`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = ${valueVar}.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(${valueVar}, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} === true) size += ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${valueVar} === true) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = 1;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, valueVar);
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
` const _val = ${valueVar} >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${valueVar} >>> 0`, ' '),
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0n) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0n) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${valueVar});`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [` const ${valueVar} = obj.${name};`],
|
||||
size: [` if (${valueVar} != null && ${valueVar} !== 0) size += ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${valueVar} != null && ${valueVar} !== 0) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${valueVar};`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
|
||||
function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock {
|
||||
const { name, fieldNumber, typeName, wireType, isMessage } = field;
|
||||
const arrayVar = `_f${index}`;
|
||||
const cacheVar = `_c${index}`;
|
||||
const tagWireType = isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType;
|
||||
const tagLength = computeTagBytes(fieldNumber, tagWireType).length;
|
||||
|
||||
if (isMessage) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` ${cacheVar} = new Array(${arrayVar}.length);`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = protobuf_encode_${typeName}(${arrayVar}[_i]);`,
|
||||
` ${cacheVar}[_i] = _data;`,
|
||||
` const _len = _data.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${cacheVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'string') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`, ` let ${cacheVar};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` ${cacheVar} = new Array(${arrayVar}.length);`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _len = __utf8Len(${arrayVar}[_i]);`,
|
||||
` ${cacheVar}[_i] = _len;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _len = ${cacheVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
writeVarint('_len', ' '),
|
||||
` offset = __utf8Write(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bytes') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${arrayVar}[_i];`,
|
||||
` const _len = _data.length;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_len', ' '),
|
||||
` size += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _data = ${arrayVar}[_i];`,
|
||||
writeTag(fieldNumber, 2, ' '),
|
||||
` const _len = _data.length;`,
|
||||
writeVarint('_len', ' '),
|
||||
` buf.set(_data, offset);`,
|
||||
` offset += _len;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'bool') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 1};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` buf[offset++] = ${arrayVar}[_i] ? 1 : 0;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isVarint64(typeName)) {
|
||||
const bigintExpr = bigintVarintExpr(typeName, `${arrayVar}[_i]`);
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
` size += ${tagLength};`,
|
||||
` size += __varint64Size(_val);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${bigintExpr};`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
` offset = __writeVarint64(buf, offset, _val);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'sint_32') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`((${arrayVar}[_i] << 1) ^ (${arrayVar}[_i] >> 31)) >>> 0`, ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Varint) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
` const _val = ${arrayVar}[_i] >>> 0;`,
|
||||
` size += ${tagLength};`,
|
||||
varintSize('_val', ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 0, ' '),
|
||||
writeVarint(`${arrayVar}[_i] >>> 0`, ' '),
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'float') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` offset = __writeFloat32(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit32) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 4};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 5, ' '),
|
||||
` const _val = ${arrayVar}[_i];`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (typeName === 'double') {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFloat64(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (isFixed64BigInt(typeName)) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` offset = __writeFixed64(buf, offset, ${arrayVar}[_i]);`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
if (wireType === WireType.Bit64) {
|
||||
return {
|
||||
declare: [` const ${arrayVar} = obj.${name};`],
|
||||
size: [` if (${arrayVar} != null && ${arrayVar}.length > 0) size += ${arrayVar}.length * ${tagLength + 8};`],
|
||||
write: [
|
||||
` if (${arrayVar} != null && ${arrayVar}.length > 0) {`,
|
||||
` for (let _i = 0; _i < ${arrayVar}.length; _i++) {`,
|
||||
writeTag(fieldNumber, 1, ' '),
|
||||
` const _val = ${arrayVar}[_i];`,
|
||||
` buf[offset++] = _val & 0xff;`,
|
||||
` buf[offset++] = (_val >> 8) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 16) & 0xff;`,
|
||||
` buf[offset++] = (_val >> 24) & 0xff;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` buf[offset++] = 0;`,
|
||||
` }`,
|
||||
` }`,
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return { declare: [], size: [], write: [] };
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import type { MessageRegistry } from '../ast/types.js';
|
||||
import { generateEncoder } from './encoder.js';
|
||||
import { generateDecoder } from './decoder.js';
|
||||
|
||||
/** Shared preamble: UTF-8 string helpers plus TextDecoder for decode. */
|
||||
const CODEGEN_PREAMBLE = `const __td = new TextDecoder();
|
||||
const __scratch = new DataView(new ArrayBuffer(8));
|
||||
function __utf8Len(value) {
|
||||
let length = 0;
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
const code = value.charCodeAt(i);
|
||||
if (code < 0x80) {
|
||||
length++;
|
||||
continue;
|
||||
}
|
||||
if (code < 0x800) {
|
||||
length += 2;
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xd800) {
|
||||
if (i + 1 < value.length) {
|
||||
const next = value.charCodeAt(i + 1);
|
||||
if ((next & 0xfc00) === 0xdc00) {
|
||||
length += 4;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
length += 3;
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xdc00) {
|
||||
length += 3;
|
||||
continue;
|
||||
}
|
||||
length += 3;
|
||||
}
|
||||
return length;
|
||||
}
|
||||
function __utf8Write(buf, offset, value) {
|
||||
for (let i = 0; i < value.length; i++) {
|
||||
let code = value.charCodeAt(i);
|
||||
if (code < 0x80) {
|
||||
buf[offset++] = code;
|
||||
continue;
|
||||
}
|
||||
if (code < 0x800) {
|
||||
buf[offset++] = 0xc0 | (code >> 6);
|
||||
buf[offset++] = 0x80 | (code & 0x3f);
|
||||
continue;
|
||||
}
|
||||
if ((code & 0xfc00) === 0xd800) {
|
||||
if (i + 1 < value.length) {
|
||||
const next = value.charCodeAt(i + 1);
|
||||
if ((next & 0xfc00) === 0xdc00) {
|
||||
const point = ((code - 0xd800) << 10) + (next - 0xdc00) + 0x10000;
|
||||
buf[offset++] = 0xf0 | (point >> 18);
|
||||
buf[offset++] = 0x80 | ((point >> 12) & 0x3f);
|
||||
buf[offset++] = 0x80 | ((point >> 6) & 0x3f);
|
||||
buf[offset++] = 0x80 | (point & 0x3f);
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
code = 0xfffd;
|
||||
} else if ((code & 0xfc00) === 0xdc00) {
|
||||
code = 0xfffd;
|
||||
}
|
||||
buf[offset++] = 0xe0 | (code >> 12);
|
||||
buf[offset++] = 0x80 | ((code >> 6) & 0x3f);
|
||||
buf[offset++] = 0x80 | (code & 0x3f);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
function __varint64Size(value) {
|
||||
let size = 1;
|
||||
while (value > 0x7fn) {
|
||||
value >>= 7n;
|
||||
size++;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
function __writeVarint64(buf, offset, value) {
|
||||
while (value > 0x7fn) {
|
||||
buf[offset++] = Number((value & 0x7fn) | 0x80n);
|
||||
value >>= 7n;
|
||||
}
|
||||
buf[offset++] = Number(value);
|
||||
return offset;
|
||||
}
|
||||
function __zigZagEncode64(value) {
|
||||
value = BigInt.asIntN(64, value);
|
||||
return BigInt.asUintN(64, (value << 1n) ^ (value >> 63n));
|
||||
}
|
||||
function __zigZagDecode64(value) {
|
||||
return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n));
|
||||
}
|
||||
function __writeFloat32(buf, offset, value) {
|
||||
__scratch.setFloat32(0, value, true);
|
||||
buf[offset++] = __scratch.getUint8(0);
|
||||
buf[offset++] = __scratch.getUint8(1);
|
||||
buf[offset++] = __scratch.getUint8(2);
|
||||
buf[offset++] = __scratch.getUint8(3);
|
||||
return offset;
|
||||
}
|
||||
function __readFloat32(data, offset) {
|
||||
__scratch.setUint8(0, data[offset]);
|
||||
__scratch.setUint8(1, data[offset + 1]);
|
||||
__scratch.setUint8(2, data[offset + 2]);
|
||||
__scratch.setUint8(3, data[offset + 3]);
|
||||
return __scratch.getFloat32(0, true);
|
||||
}
|
||||
function __writeFloat64(buf, offset, value) {
|
||||
__scratch.setFloat64(0, value, true);
|
||||
buf[offset++] = __scratch.getUint8(0);
|
||||
buf[offset++] = __scratch.getUint8(1);
|
||||
buf[offset++] = __scratch.getUint8(2);
|
||||
buf[offset++] = __scratch.getUint8(3);
|
||||
buf[offset++] = __scratch.getUint8(4);
|
||||
buf[offset++] = __scratch.getUint8(5);
|
||||
buf[offset++] = __scratch.getUint8(6);
|
||||
buf[offset++] = __scratch.getUint8(7);
|
||||
return offset;
|
||||
}
|
||||
function __readFloat64(data, offset) {
|
||||
__scratch.setUint8(0, data[offset]);
|
||||
__scratch.setUint8(1, data[offset + 1]);
|
||||
__scratch.setUint8(2, data[offset + 2]);
|
||||
__scratch.setUint8(3, data[offset + 3]);
|
||||
__scratch.setUint8(4, data[offset + 4]);
|
||||
__scratch.setUint8(5, data[offset + 5]);
|
||||
__scratch.setUint8(6, data[offset + 6]);
|
||||
__scratch.setUint8(7, data[offset + 7]);
|
||||
return __scratch.getFloat64(0, true);
|
||||
}
|
||||
function __writeFixed64(buf, offset, value) {
|
||||
value = BigInt.asUintN(64, value);
|
||||
buf[offset++] = Number(value & 0xffn);
|
||||
buf[offset++] = Number((value >> 8n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 16n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 24n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 32n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 40n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 48n) & 0xffn);
|
||||
buf[offset++] = Number((value >> 56n) & 0xffn);
|
||||
return offset;
|
||||
}
|
||||
function __readFixed64(data, offset) {
|
||||
return BigInt(data[offset])
|
||||
| (BigInt(data[offset + 1]) << 8n)
|
||||
| (BigInt(data[offset + 2]) << 16n)
|
||||
| (BigInt(data[offset + 3]) << 24n)
|
||||
| (BigInt(data[offset + 4]) << 32n)
|
||||
| (BigInt(data[offset + 5]) << 40n)
|
||||
| (BigInt(data[offset + 6]) << 48n)
|
||||
| (BigInt(data[offset + 7]) << 56n);
|
||||
}`;
|
||||
|
||||
/**
|
||||
* Generate fully self-contained encode/decode source code.
|
||||
* No runtime imports needed — all wire-format logic is inlined.
|
||||
*/
|
||||
export function generateCode(registry: MessageRegistry): string {
|
||||
if (registry.size === 0) return '';
|
||||
const parts: string[] = [CODEGEN_PREAMBLE];
|
||||
for (const msg of registry.values()) {
|
||||
parts.push(generateEncoder(msg, registry));
|
||||
parts.push(generateDecoder(msg, registry));
|
||||
}
|
||||
return parts.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Protobuf wire format helpers — used directly by wire.test.ts
|
||||
// The generated code no longer depends on these (everything is inlined).
|
||||
|
||||
export function encodeVarint(value: number, buf: number[]): void {
|
||||
value = value >>> 0;
|
||||
while (value > 0x7f) {
|
||||
buf.push((value & 0x7f) | 0x80);
|
||||
value = value >>> 7;
|
||||
}
|
||||
buf.push(value & 0x7f);
|
||||
}
|
||||
|
||||
export function decodeVarint(data: Uint8Array, offset: number): [number, number] {
|
||||
let result = 0;
|
||||
let shift = 0;
|
||||
let byte: number;
|
||||
do {
|
||||
byte = data[offset++];
|
||||
result |= (byte & 0x7f) << shift;
|
||||
shift += 7;
|
||||
} while (byte & 0x80);
|
||||
return [result >>> 0, offset];
|
||||
}
|
||||
|
||||
export function writeTag(fieldNumber: number, wireType: number, buf: number[]): void {
|
||||
encodeVarint((fieldNumber << 3) | wireType, buf);
|
||||
}
|
||||
|
||||
export function writeString(value: string, buf: number[]): void {
|
||||
const encoded = new TextEncoder().encode(value);
|
||||
encodeVarint(encoded.length, buf);
|
||||
for (let i = 0; i < encoded.length; i++) buf.push(encoded[i]);
|
||||
}
|
||||
|
||||
export function readString(data: Uint8Array, offset: number, length: number): string {
|
||||
return new TextDecoder().decode(data.subarray(offset, offset + length));
|
||||
}
|
||||
|
||||
export function writeBytes(value: Uint8Array, buf: number[]): void {
|
||||
encodeVarint(value.length, buf);
|
||||
for (let i = 0; i < value.length; i++) buf.push(value[i]);
|
||||
}
|
||||
|
||||
export function skipField(data: Uint8Array, offset: number, wireType: number): number {
|
||||
switch (wireType) {
|
||||
case 0: while (data[offset] & 0x80) offset++; return offset + 1;
|
||||
case 1: return offset + 8;
|
||||
case 2: { const [len, o] = decodeVarint(data, offset); return o + len; }
|
||||
case 5: return offset + 4;
|
||||
default: throw new Error(`Unknown wire type: ${wireType}`);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user