diff --git a/@ether/$/deflate/Deflate.ray b/@ether/$/deflate/Deflate.ray index c47ca383e..02d8d87e7 100644 --- a/@ether/$/deflate/Deflate.ray +++ b/@ether/$/deflate/Deflate.ray @@ -4,19 +4,78 @@ Deflate := class: Language { // Huffman codes given by their lengths alone: shorter codes first, equal lengths in symbol order, each the next binary number (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.2) static Huffman := class lengths: Decimal[] { - codes => lengths.enumerate{.value > 0}.sort_by((.value, .index)).reduce(acc = [] => [acc, - (symbol: .index, bits: ((acc.empty ? 0 : (acc.last.bits + 1) * 2 ^ (.value - acc.last.bits.length)) as Binary).padded(.value))]) + table := None + codes => + (.table := coded) unless .table + .table + coded => + made := [] + code := 0 + width := 1 + while width <= 15 { + at := lengths.head + index := 0 + while at { + if at.value == width { + made.append((symbol: index, bits: code.binary(width))) + code = code + 1 + } + index = index + 1 + at = at.next + } + code = code * 2 + width = width + 1 + } + made // A symbol is read as the one code whose bits come next, most significant bit first, and written as its code (https://www.rfc-editor.org/rfc/rfc1951#section-3.1.1) - Symbol => Binary{. is codes.bits#} as (bits => codes{.bits == bits}.first.symbol) - bits (symbol: Decimal) => codes{.symbol == symbol}.first.bits + Symbol => Coded(codes) + // (whether the lengths fill the code: a code shorter than all, or one of codes past what the bits hold, is not one) + fills => + code := 0 + width := 1 + while width <= 15 { + at := lengths.head + while at { + (code = code + 1) if at.value == width + at = at.next + } + code = code * 2 + width = width + 1 + } + code == 65536 + bits (symbol) => codes.find((code) => code.symbol == symbol).bits // Lengths fitted to frequencies: the two least frequent join until one is left, each join one bit deeper (Huffman 1952, https://www.rfc-editor.org/rfc/rfc1951#section-3.2.2) - static fitted (frequencies: Number[]) => (1.. 0}.count).reduce(held = (nodes: frequencies.enumerate{.value > 0}.map((weight: .value, symbols: [.index])), lengths: [0] * frequencies.count) => - held.nodes.sort_by(.weight) -- (sorted => [sorted[0].symbols, sorted[1].symbols].flatten -- (joined => ( - nodes: [sorted[2..], (weight: sorted[0].weight + sorted[1].weight, symbols: joined)], - lengths: held.lengths.enumerate.map(.value + (.index is joined# ? 1 : 0)))))) - .lengths.enumerate.map(frequencies[.index] > 0 ? .value max 1 : 0) -- Huffman(.) + static fitted (frequencies) => + lengths := [0] * frequencies.count + nodes := [] + index := 0 + at := frequencies.head + while at { + (nodes.append(Deflate.Weighted(at.value, [index]))) if at.value > 0 + index = index + 1 + at = at.next + } + while nodes.count > 1 { + sorted := nodes.sort_by((node) => node.weight) + joined := [sorted.first.symbols, sorted.rest.first.symbols].flatten + joined.for((symbol) => Deflate.deepened(lengths, symbol)) + nodes = sorted.rest.rest + nodes.append(Deflate.Weighted(sorted.first.weight + sorted.rest.first.weight, joined)) + } + (Deflate.deepened(lengths, nodes.first.symbols.first)) if (nodes.count == 1) && (nodes.first.symbols.count == 1) + Deflate.Huffman(lengths) } + // (a node of `fitted`: how often its symbols are, and which they are; one symbol one bit deeper) + static Weighted := class (weight, symbols) + static deepened (lengths, symbol) => + at := lengths.head + left := symbol + while left > 0 { + at = at.next + left = left - 1 + } + at.value = at.value + 1 // Lengths 3..258 as codes 257..285 and distances 1..32768 as codes 0..29: each code's base and extra bits (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.5) static LengthBases := [(3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 1), (13, 1), (15, 1), (17, 1), (19, 2), (23, 2), (27, 2), (31, 2), @@ -26,28 +85,45 @@ Deflate := class: Language { // A literal byte, or a copy of length bytes from distance bytes back (https://www.rfc-editor.org/rfc/rfc1951#section-2) static Literal := class byte: Byte - static Copy := class length: Decimal{3 <= . <= 258}, distance: Decimal{1 <= . <= 32768} + static Copy := class (length: Decimal{(. >= 3) && (. <= 258)}, distance: Decimal{(. >= 1) && (. <= 32768)}) - // Data elements other than Huffman codes are packed starting with their least significant bit, so they read reversed (https://www.rfc-editor.org/rfc/rfc1951#section-3.1.1) + // Data elements other than Huffman codes are fixed_stream starting with their least significant bit, so they read reversed (https://www.rfc-editor.org/rfc/rfc1951#section-3.1.1) static Data := class ( elements: ( (literal: literals.Symbol{< 256}) - | (length_code: literals.Symbol{257 <= . <= 285}, length_extra: <-Binary{length == LengthBases[length_code - 257].1}, - distance_code: distances.Symbol{< 30}, distance_extra: <-Binary{length == DistanceBases[distance_code].1}) + | (length_code: literals.Symbol{(. >= 257) && (. <= 285)}, length_extra: <-Binary{length == Deflate.LengthBases[length_code - 257].last}, + distance_code: distances.Symbol{< 30}, distance_extra: <-Binary{length == Deflate.DistanceBases[distance_code].last}) )[], // End-of-block (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.5) literals.Symbol{== 256} ) { - values => elements.map(. -- (.literal != None ? Literal(.literal) - : Copy(LengthBases[.length_code - 257].0 + .length_extra, DistanceBases[.distance_code].0 + .distance_extra))) + values => elements.map((element) => Deflate.value_of(element)) } - static coded (value: Literal | Copy) => value is Literal ? (literal: value.byte) - : LengthBases.enumerate{.value.0 <= value.length}.last -- (length => DistanceBases.enumerate{.value.0 <= value.distance}.last -- (distance => ( - length_code: length.index + 257, length_extra: value.length - length.value.0, - distance_code: distance.index, distance_extra: value.distance - distance.value.0))) + static value_of (element) => (element.literal !== None) ? Literal(element.literal) + : Copy((LengthBases[element.length_code - 257].first) + element.length_extra, (DistanceBases[element.distance_code].first) + element.distance_extra) + static coded (value) => + if value is Literal { + return Element(literal: value.byte) + } + length := Deflate.base_of(LengthBases, value.length) + distance := Deflate.base_of(DistanceBases, value.distance) + Element(length_code: length + 257, length_extra: value.length - (LengthBases[length].first), distance_code: distance, distance_extra: value.distance - (DistanceBases[distance].first)) + // (an element of `Data` as `coded` writes it: a literal, or a length and a distance, each a code and its extra bits) + static Element := class (literal, length_code, length_extra, distance_code, distance_extra) + // (the last code whose base is not past a value) + static base_of (bases, value) => + found := 0 + index := 0 + at := bases.head + while at { + (found = index) if at.value.first <= value + index = index + 1 + at = at.next + } + found // Non-compressed block: to the byte boundary, LEN, its one's complement NLEN, then LEN bytes (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.4) - static Stored := class (Binary{length < 8 && (at + length) % 8 == 0}, size: <-Binaryâ‚�₆ = bytes.count, <-Binaryâ‚�₆{== 2 ^ 16 - 1 - size}, bytes: (<-Byte)[]{length == size}) + static Stored := class (padding: Binary{(length < 8) && (((at + length) % 8) == 0)}, size: <-Binaryâ‚�₆ = bytes.count, <-Binaryâ‚�₆{== 65535 - size}, bytes: (<-Byte)[]{length == size}) // Fixed Huffman codes (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.6) static fixed_literals := Huffman([[8] * 144, [9] * 112, [7] * 24, [8] * 8].flatten) @@ -62,75 +138,193 @@ Deflate := class: Language { | (code.Symbol{== 18}, many: <-Binary₇) )[] ) { - values => entries.reduce(acc = [] => [acc, .length != None ? [.length] : .again != None ? [acc.last] * (.again + 3) : [0] * (.zeros != None ? .zeros + 3 : .many + 11)].flatten) + values => + (return None) unless code.fills + made := [] + at := entries.head + while at { + entry := at.value + if entry.length !== None { + made.append(entry.length) + } elsif entry.again !== None { + (return None) if made.empty + made.joined([made.last] * (entry.again + 3)) + } elsif entry.zeros !== None { + made.joined([0] * (entry.zeros + 3)) + } else { + made.joined([0] * (entry.many + 11)) + } + at = at.next + } + made } + // (an entry of `CodeLengths` as `dynamic` writes it: a run of zeros as 17 or 18, a run of a length as 16 after it) + static Entry := class (length, again, zeros, many) + static entries_of (lengths) => + made := [] + at := lengths.head + while at { + value := at.value + run := 1 + ahead := at.next + while ahead && (ahead.value == value) { + run = run + 1 + ahead = ahead.next + } + at = ahead + if (value == 0) && (run >= 3) { + while run >= 11 { + n := (run > 138) ? 138 : run + made.append(Deflate.Entry(many: n - 11)) + run = run - n + } + if run >= 3 { + made.append(Deflate.Entry(zeros: run - 3)) + run = 0 + } + } else { + made.append(Deflate.Entry(length: value)) + run = run - 1 + while run >= 3 { + n := (run > 6) ? 6 : run + made.append(Deflate.Entry(again: n - 3)) + run = run - n + } + } + while run > 0 { + made.append(Deflate.Entry(length: value)) + run = run - 1 + } + } + made + static symbol_of (entry) => (entry.length !== None) ? entry.length : ((entry.again !== None) ? 16 : ((entry.zeros !== None) ? 17 : 18)) + // Dynamic Huffman codes: HLIT, HDIST, HCLEN, the code length code in its own order, then both codes' lengths as one sequence (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.7) static Order := [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] static Dynamic := class ( hlit: <-Binaryâ‚… = literals.lengths.count - 257, hdist: <-Binaryâ‚… = distances.lengths.count - 1, hclen: <-Binaryâ‚„ = 15, - sizes: (<-Binary₃)[]{length == hclen + 4} = Order.map(length_code.lengths[.] ?? 0), - lengths: CodeLengths{values.count == hlit + 257 + hdist + 1} = CodeLengths(entries: [literals.lengths, distances.lengths].flatten.map((length: .))), - data: Data + sizes: (<-Binary₃)[]{length == hclen + 4} = Deflate.Order.map((symbol) => length_code.lengths[symbol] ?? 0), + lengths: Deflate.CodeLengths{(hlit + 257 + hdist + 1) == values.count} = Deflate.CodeLengths(length_code, [literals.lengths, distances.lengths].flatten.map((length) => Deflate.Entry(length))), + data: Deflate.Data ) { - length_code => Huffman((0..18).map(symbol => sizes[Order.index_of(symbol)] ?? 0)) - literals => Huffman(lengths.values[.. Huffman(lengths.values[hlit + 257..]) + length_code => Deflate.Huffman((0..18).map((symbol) => sizes[Deflate.Order.index_of(symbol)] ?? 0)) + literals => Deflate.Huffman(lengths.values.slice(0, hlit + 257)) + distances => Deflate.Huffman(lengths.values.slice(hlit + 257, lengths.values.count)) } // Block header: BFINAL, then BTYPE: 0 stored, 1 fixed codes, 2 dynamic codes (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.3) static Block := class ( final: Binaryâ‚� as boolean = false, kind: <-Binaryâ‚‚{< 3} = 0, - (stored: Stored) if kind == 0, - (data: Data) if kind == 1, - (dynamic: Dynamic) if kind == 2 + (stored: Deflate.Stored) if kind == 0, + (data: Deflate.Data) if kind == 1, + (dynamic: Deflate.Dynamic) if kind == 2 ) { - values => stored ? stored.bytes.map(Literal(.)) : (data ?? dynamic.data).values + values => stored ? stored.bytes.map((byte) => Deflate.Literal(byte)) : (data ?? dynamic.data).values } // Blocks up to the final one, padded to a byte; each byte's bits are taken least significant first (https://www.rfc-editor.org/rfc/rfc1951#section-3.1.1, https://www.rfc-editor.org/rfc/rfc1951#section-3.2.3) - static Stream := class (blocks: Block[]{.last.final && !.[..<-1].some(.final)}, Binary{length < 8 && (at + length) % 8 == 0}) { + static Stream := class (blocks: Deflate.Block[]{!.empty && .last.final}, padding: Binary{(length < 8) && (((at + length) % 8) == 0)}) { // A copy may reach back into earlier blocks, and may overlap what it writes (https://www.rfc-editor.org/rfc/rfc1951#section-2, https://www.rfc-editor.org/rfc/rfc1951#section-3.2.3) - bytes => blocks.values.flatten.reduce(out = [] => copied(out, .)) - static copied (out: Byte[], value: Literal | Copy) => value is Literal ? [out, value.byte] - : (0.. [held, held[held.count - value.distance]]) + bytes => + out := [] + at := blocks.head + while at { + value := at.value.values.head + while value { + (return None) unless Deflate.Stream.copied(out, value.value) + value = value.next + } + at = at.next + } + out + // (a copy reaching before the first byte is no copy: None) + static copied (out, value) => + if value is Deflate.Literal { + return out.append(value.byte) + } + (return None) if value.distance > out.count + from := out.tail + back := value.distance - 1 + while back > 0 { + from = from.previous + back = back - 1 + } + left := value.length + while left > 0 { + out.append(from.value) + from = from.next + left = left - 1 + } + out - static (bytes: Byte[]) as (=== Stream) => bytes.map(<-.).flatten as Stream - as (=== Byte[]) => (this as Binary).chunk(8).map(<-. as Byte) + static from (bytes) => bytes.listing ? Deflate.Stream.bits_read(bytes.map((byte) => byte.binary(8).reversed).join("")) : None + written => .binary.pieces(8).map((eight) => eight.reversed.unsigned) } // A stored block holds at most 65535 bytes (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.4) - static blocked (bytes: Byte[]) => (bytes.chunk(2 ^ 16 - 1) -- (.empty ? [[]] : .)) -- (chunks => - chunks.enumerate.map(Block(final: .index == chunks.count - 1, kind: 0, stored: Stored(bytes: .value)))) + static blocked (bytes) => + made := [] + from := 0 + loop { + to := ((from + 65535) < bytes.count) ? (from + 65535) : bytes.count + made.append(Block(final: to == bytes.count, kind: 0, stored: Stored(bytes: bytes.slice(from, to)))) + (break) if to == bytes.count + from = to + } + made // LZ77: at each position the longest earlier match of at least 3 bytes, at most 258 long and 32768 back (https://www.rfc-editor.org/rfc/rfc1951#section-4) - static parsed (bytes: Byte[], at: Number = 0) => at >= bytes.count ? [] - : ((0 max at - 32768).. (length: Encoding.common(bytes[from..], bytes[at..<(at + 258 min bytes.count)]), distance: at - from)).max_by(.length)#.first -- (best => - best && best.length >= 3 ? [Copy(best.length, best.distance), parsed(bytes, at + best.length)] : [Literal(bytes[at]), parsed(bytes, at + 1)]) - - static fixed (values: (Literal | Copy)[]) => Data(elements: values.map(coded(.))) - static dynamic (values: (Literal | Copy)[]) => values.map(coded(.)) -- (codes => - Huffman.fitted((0..<286).map(symbol => codes{(.literal ?? .length_code) == symbol}.count + (symbol == 256 ? 1 : 0))) -- (literals => - Huffman.fitted((0..<30).map(symbol => codes{.distance_code == symbol}.count) -- (.some(> 0) ? . : [1])) -- (distances => - Dynamic(literals: literals, distances: distances, data: Data(elements: codes), - length_code: Huffman.fitted((0..18).map(length => [literals.lengths, distances.lengths].flatten{== length}.count)))))) - - // A block is written with fixed codes, or with codes fitted to its own frequencies, when that is shorter; fitted codes are at most 15 bits, 7 for the code lengths (https://www.rfc-editor.org/rfc/rfc1951#section-3.2.6, https://www.rfc-editor.org/rfc/rfc1951#section-3.2.7) - static Optimizations := { - {block: Block{kind == 0 && (Block(final, kind: 1, data: fixed(parsed(stored.bytes))) as Binary).length < (this as Binary).length}} => - Block(final: block.final, kind: 1, data: fixed(parsed(block.stored.bytes))) - {block: Block{kind == 1 && dynamic(values) -- (.literals.lengths.max <= 15 && .distances.lengths.max <= 15 && .length_code.lengths.max <= 7 - && (Block(final, kind: 2, dynamic: .) as Binary).length < (this as Binary).length)}} => - Block(final: block.final, kind: 2, dynamic: dynamic(block.values)) - } + static parsed (bytes) => + text := bytes.latin1 + made := [] + at := 0 + while at < text.count { + length := 0 + distance := 0 + loop { + (break) if (length >= 258) || ((at + length + 1) > text.count) + found := text.last_index_of(text.substring(at, at + length + 1), at - 1) + (break) if (found < 0) || (found >= at) || ((at - found) > 32768) + length = length + 1 + distance = at - found + } + if length >= 3 { + made.append(Copy(length, distance)) + at = at + length + } else { + made.append(Literal(text.code_at(at))) + at = at + 1 + } + } + made + static fixed (values) => Data(literals: fixed_literals, distances: fixed_distances, elements: values.map((value) => Deflate.coded(value))) + // (codes fitted to the values' own frequencies, the end of the block once; a distance code even when no copy needs one) + static dynamic (values) => + codes := values.map((value) => Deflate.coded(value)) + literals := Huffman.fitted([codes.map((code) => code.literal ?? code.length_code), [256]].flatten.tally(286)) + distance_counts := codes.map((code) => code.distance_code ?? 30).tally(30) + distances := Huffman.fitted((distance_counts.maximum > 0) ? distance_counts : [1]) + entries := entries_of([literals.lengths, distances.lengths].flatten) + length_code := Huffman.fitted(entries.map((entry) => Deflate.symbol_of(entry)).tally(19)) + Dynamic(literals: literals, distances: distances, length_code: length_code, lengths: CodeLengths(length_code, entries), data: Data(literals: literals, distances: distances, elements: codes)) + // (fitted codes are at most 15 bits, 7 for the code lengths: https://www.rfc-editor.org/rfc/rfc1951#section-3.2.7) + static fits (dynamic) => (dynamic.literals.lengths.maximum <= 15) && (dynamic.distances.lengths.maximum <= 15) && (dynamic.length_code.lengths.maximum <= 7) - level := { - {stream: Stream} => stream.bytes - } - written := Optimizations + { - {writing: Language.Writing} => Stream(blocks: blocked(writing.value as Byte[])) - } + // (the bytes a stream inflates to; the bytes of a stream holding these: stored, with the fixed codes, or with codes fitted to + // them, whichever is shortest) + static inflated (bytes) => Stream.from(bytes).bytes + static deflated (bytes) => + stored_stream := Stream(blocks: blocked(bytes)) + (return stored_stream.written) if bytes.empty + values := parsed(bytes) + fixed_stream := Stream(blocks: [Block(final: true, kind: 1, data: fixed(values))]) + shortest := (fixed_stream.binary.count < stored_stream.binary.count) ? fixed_stream : stored_stream + fitted := dynamic(values) + (return shortest.written) unless fits(fitted) + dynamic_stream := Stream(blocks: [Block(final: true, kind: 2, dynamic: fitted)]) + (dynamic_stream.binary.count < shortest.binary.count) ? dynamic_stream.written : shortest.written } diff --git a/@ether/poc/deflate/.gitignore b/@ether/poc/deflate/.gitignore new file mode 100644 index 000000000..89f9ac04a --- /dev/null +++ b/@ether/poc/deflate/.gitignore @@ -0,0 +1 @@ +out/ diff --git a/@ether/poc/deflate/bad/btype3.deflate b/@ether/poc/deflate/bad/btype3.deflate new file mode 100644 index 000000000..303e398c8 --- /dev/null +++ b/@ether/poc/deflate/bad/btype3.deflate @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/@ether/poc/deflate/bad/far.deflate b/@ether/poc/deflate/bad/far.deflate new file mode 100644 index 000000000..34168c74d Binary files /dev/null and b/@ether/poc/deflate/bad/far.deflate differ diff --git a/@ether/poc/deflate/bad/fixed286.deflate b/@ether/poc/deflate/bad/fixed286.deflate new file mode 100644 index 000000000..955f7f9d7 --- /dev/null +++ b/@ether/poc/deflate/bad/fixed286.deflate @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/@ether/poc/deflate/bad/manifest.txt b/@ether/poc/deflate/bad/manifest.txt new file mode 100644 index 000000000..c0c099bbc --- /dev/null +++ b/@ether/poc/deflate/bad/manifest.txt @@ -0,0 +1,7 @@ +btype3.deflate 3 invalid block type +nlen.deflate 40 invalid stored block lengths +truncated.deflate 3 incomplete or truncated stream +fixed286.deflate 11 invalid literal/length code +far.deflate - invalid distance too far back +repeat.deflate - invalid bit length repeat +oversubscribed.deflate - invalid code lengths set diff --git a/@ether/poc/deflate/bad/nlen.deflate b/@ether/poc/deflate/bad/nlen.deflate new file mode 100644 index 000000000..0f61701e3 Binary files /dev/null and b/@ether/poc/deflate/bad/nlen.deflate differ diff --git a/@ether/poc/deflate/bad/oversubscribed.deflate b/@ether/poc/deflate/bad/oversubscribed.deflate new file mode 100644 index 000000000..a5c144af6 Binary files /dev/null and b/@ether/poc/deflate/bad/oversubscribed.deflate differ diff --git a/@ether/poc/deflate/bad/repeat.deflate b/@ether/poc/deflate/bad/repeat.deflate new file mode 100644 index 000000000..9a6a1c1ca Binary files /dev/null and b/@ether/poc/deflate/bad/repeat.deflate differ diff --git a/@ether/poc/deflate/bad/truncated.deflate b/@ether/poc/deflate/bad/truncated.deflate new file mode 100644 index 000000000..3410062ba --- /dev/null +++ b/@ether/poc/deflate/bad/truncated.deflate @@ -0,0 +1 @@ +c \ No newline at end of file diff --git a/@ether/poc/deflate/boot.mts b/@ether/poc/deflate/boot.mts new file mode 100644 index 000000000..b7ab8f098 --- /dev/null +++ b/@ether/poc/deflate/boot.mts @@ -0,0 +1,39 @@ +// language3 as `site3.mts` boots it: the entrypoint with the host's operators where its logic begins, the host's kinds, the +// core library in the order it needs itself, the host's rules again after it (`KINDS_AFTER`), then the files in `LOAD`. +const ether = process.env.ETHER!; +const { Program, Text } = await import(`${ether}/v0.ts/src/language3.ts`); +const fs = await import('node:fs'), path = await import('node:path'); + +export { Program }; +export const booted = async () => { + const entry = fs.readFileSync(path.join(ether, 'ray/.entrypoint.ray2'), 'utf8'), kinds = fs.readFileSync(path.join(ether, 'v0.ts/src/js3.kinds.ray'), 'utf8'); + const ops = kinds.indexOf('// What both answer'), made_of = kinds.indexOf('// What a number or text is made of'), logic = entry.indexOf('// What a value answers to `?`'); + const source = new Text.Source('@ether/ray/.entrypoint.ray2'); + source.value = entry.slice(0, logic) + kinds.slice(ops, made_of) + '\n' + entry.slice(logic); + const program: any = new Program(source); + await program.compile(); + program.run(kinds.slice(0, ops) + '\n' + kinds.slice(made_of), { node: program.global }); + if (process.env.STEPS) { const read = program.read, limit = Number(process.env.STEPS); program.read = function (...args: unknown[]) { if (++program.steps > limit) throw new Error('ran away at ' + String(args[0]).slice(0, 80)); return read.apply(this, args); }; program.steps = 0; } + const statements = (file: string) => program.code(fs.readFileSync(file, 'utf8')).statements.filter((statement: string) => statement.trim() && !statement.trim().startsWith('//') && !/^@[\w./-]+$/.test(statement.trim())); + const quietly = (file: string) => { for (const statement of statements(file)) { program.steps = 0; try { program.run(statement, { node: program.global }); } catch {} } }; + const reading_order = (files: string[]): string[] => { + const texts = new Map(files.map(file => [file, fs.readFileSync(file, 'utf8')])); + const defines = (text: string) => new Set([...text.matchAll(/^([A-Za-z_][\w-]*)(?:\s*<[^>\n]*>)?\s*(?:\^[\w.]+\s*)?:=/gm)].map(m => m[1])); + const info = files.map(file => ({ file, defines: defines(texts.get(file)!), uses: new Set(texts.get(file)!.match(/[A-Za-z_][\w]*/g) ?? []) })); + const needs = new Map(info.map(f => [f.file, new Set(info.filter(g => g !== f && [...g.defines].some(name => f.uses.has(name) && !f.defines.has(name))).map(g => g.file))])); + const order: string[] = [], left = new Set(files); + while (left.size > 0) { const waiting = (file: string) => [...needs.get(file)!].filter(other => left.has(other)).length; const next = [...left].sort((a, b) => waiting(a) - waiting(b) || (a < b ? -1 : 1))[0]; order.push(next); left.delete(next); } + return order; + }; + const library = path.join(ether, 'ray'); + if (!process.env.NOLIB) for (const file of reading_order(fs.readdirSync(library).filter((file: string) => file.endsWith('.ray') && !file.startsWith('.')).map((file: string) => path.join(library, file)))) quietly(file); + if (process.env.KINDS_AFTER) for (const statement of program.code(kinds).statements) { + const head = statement.split('\n')[0]; + if (!/=>\s*$/.test(head) || head.includes('{{')) continue; + program.run(statement, { node: program.global }); + const rule = program.global.rules.find((rule: any) => rule.head === program.head(head.trimEnd().slice(0, -2).trim()).head); + if (rule) { rule.id = ++Program.Node.defined; program.global.headed++; } + } + for (const file of (process.env.LOAD ?? '').split(',').filter(Boolean)) quietly(path.resolve(ether, file)); + return { program, statements }; +}; diff --git a/@ether/poc/deflate/corpus.mts b/@ether/poc/deflate/corpus.mts new file mode 100644 index 000000000..5723d4c0d --- /dev/null +++ b/@ether/poc/deflate/corpus.mts @@ -0,0 +1,67 @@ +// DP3 (`read`): each corpus stream read by `Deflate.inflated`, its SHA-256 the one `manifest.txt` has for what zlib inflates +// it to. DP4 (`rewrite`): each stream read into a `Deflate.Stream` and that same value written back, byte for byte the stream. +const { booted } = await import('./boot.mts'); +const fs = await import('node:fs'), path = await import('node:path'), crypto = await import('node:crypto'); +const { program } = await booted(); +const here = path.dirname(new URL(import.meta.url).pathname), corpus = path.join(here, 'corpus'), out = path.join(here, 'out', process.argv[2]); +fs.mkdirSync(out, { recursive: true }); +const g = { node: program.global }, none = program.run('None', g); +const run = (text: string) => { program.steps = 0; return program.run(text, g); }; +const listed = (bytes: Uint8Array) => { const list = run('Listing.new'); for (const byte of bytes) run(program.written(list) + '.append(' + byte + ')'); return list; }; +const bytes_of = (list: unknown): Uint8Array | undefined => { + if (typeof list !== 'object' || list === null || run(program.written(list) + '.listing') !== run('true')) return undefined; + const values: number[] = []; + for (let at = run(program.written(list) + '.head'); at !== none && at !== undefined; at = run(program.written(at) + '.next')) values.push(run(program.written(at) + '.value') as number); + return Uint8Array.from(values); +}; +const sha = (bytes: Uint8Array) => crypto.createHash('sha256').update(bytes).digest('hex'); +const only = process.env.ONLY?.split(','); +let failed = 0; +// DP6 (`reject`): each stream zlib rejects answers no bytes, and where reading stopped is the bit `bad/manifest.txt` gives +// (`-`: it reads, and what it means does not hold). +if (process.argv[2] === 'reject') { + for (const line of fs.readFileSync(path.join(here, 'bad', 'manifest.txt'), 'utf8').trim().split('\n')) { + const [name, stop, ...reason] = line.split(' '); + if (only && !only.some(part => name.includes(part))) continue; + let answered: Uint8Array | undefined, error = ''; + try { answered = bytes_of(run('Deflate.inflated(' + program.written(listed(fs.readFileSync(path.join(here, 'bad', name)))) + ')')); } catch (e: any) { error = String(e?.message).slice(0, 80); } + const reached = program.layouts.reached, held = !answered && !error && (stop === '-' || Number(stop) === reached); + if (!held) failed++; + console.log(held ? 'ok ' : 'FAIL', name.padEnd(24), 'stopped at bit', String(stop === '-' ? '-' : reached).padStart(3), '| zlib:', reason.join(' '), held ? '' : error || (answered ? `read ${answered.length} bytes` : `expected bit ${stop}`)); + } + console.log(failed ? `${failed} failed` : 'DP6 every stream zlib rejects is rejected'); + process.exit(failed ? 1 : 0); +} +// DP5 (`write`): each input written by `Deflate.deflated`; zlib inflates it to the input, and Ray reads it back to the input. +if (process.argv[2] === 'write') { + const zlib = await import('node:zlib'); + for (const name of fs.readdirSync(path.join(here, 'inputs')).sort()) { + if (only && !only.some(part => name.includes(part))) continue; + const input = fs.readFileSync(path.join(here, 'inputs', name)), started = performance.now(); + let written: Uint8Array | undefined, inflated: Uint8Array | undefined, read: Uint8Array | undefined, error = ''; + try { + written = bytes_of(run('Deflate.deflated(' + program.written(listed(input)) + ')')); + if (written) { fs.writeFileSync(path.join(out, name + '.deflate'), written); inflated = zlib.inflateRawSync(written); read = bytes_of(run('Deflate.inflated(' + program.written(listed(written)) + ')')); } + } catch (e: any) { error = String(e?.message).slice(0, 80); } + const held = !!inflated && !!read && sha(inflated) === sha(input) && sha(read) === sha(input); + if (!held) failed++; + console.log(held ? 'ok ' : 'FAIL', name.padEnd(14), String(input.length).padStart(5), '->', String(written?.length ?? '-').padStart(5), 'bytes', String(Math.round(performance.now() - started)).padStart(7), 'ms', held ? '' : error || 'not the input'); + } + console.log(failed ? `${failed} failed` : 'all written so zlib, and Ray, read back the input'); + process.exit(failed ? 1 : 0); +} +for (const line of fs.readFileSync(path.join(corpus, 'manifest.txt'), 'utf8').trim().split('\n')) { + const [name, , stream_sha, inflated_sha] = line.split(' '); + if (only && !only.some(part => name.includes(part))) continue; + const stream = fs.readFileSync(path.join(corpus, name)), started = performance.now(); + let got: Uint8Array | undefined, error = ''; + try { + got = process.argv[2] === 'read' ? bytes_of(run('Deflate.inflated(' + program.written(listed(stream)) + ')')) : bytes_of(run('Deflate.Stream.from(' + program.written(listed(stream)) + ').written')); + } catch (e: any) { error = String(e?.message).slice(0, 80); } + const held = got !== undefined && sha(got) === (process.argv[2] === 'read' ? inflated_sha : stream_sha); + if (got) fs.writeFileSync(path.join(out, name.replace(/\.deflate$/, process.argv[2] === 'read' ? '' : '.deflate')), got); + if (!held) failed++; + console.log(held ? 'ok ' : 'FAIL', name.padEnd(32), String(Math.round(performance.now() - started)).padStart(7), 'ms', held ? '' : error || (got ? `${got.length} bytes, not the same` : 'no bytes')); +} +console.log(failed ? `${failed} failed` : `all ${process.argv[2] === 'read' ? 'read to what zlib inflates them to' : 'written back byte for byte'}`); +process.exitCode = failed ? 1 : 0; diff --git a/@ether/poc/deflate/corpus/empty.bin.0.default.deflate b/@ether/poc/deflate/corpus/empty.bin.0.default.deflate new file mode 100644 index 000000000..f07c30dfc Binary files /dev/null and b/@ether/poc/deflate/corpus/empty.bin.0.default.deflate differ diff --git a/@ether/poc/deflate/corpus/empty.bin.1.default.deflate b/@ether/poc/deflate/corpus/empty.bin.1.default.deflate new file mode 100644 index 000000000..15294a501 Binary files /dev/null and b/@ether/poc/deflate/corpus/empty.bin.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/hello.txt.0.default.deflate b/@ether/poc/deflate/corpus/hello.txt.0.default.deflate new file mode 100644 index 000000000..6c17049d3 Binary files /dev/null and b/@ether/poc/deflate/corpus/hello.txt.0.default.deflate differ diff --git a/@ether/poc/deflate/corpus/hello.txt.1.default.deflate b/@ether/poc/deflate/corpus/hello.txt.1.default.deflate new file mode 100644 index 000000000..0910d317d Binary files /dev/null and b/@ether/poc/deflate/corpus/hello.txt.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/manifest.txt b/@ether/poc/deflate/corpus/manifest.txt new file mode 100644 index 000000000..edb8ae998 --- /dev/null +++ b/@ether/poc/deflate/corpus/manifest.txt @@ -0,0 +1,22 @@ +empty.bin.0.default.deflate 5 f067985d352d2da6dfaef4844a66d06c5371ecbd9530a4d195ac599fef8b3427 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +empty.bin.1.default.deflate 2 9b4fb24edd6d1d8830e272398263cdbf026b97392cc35387b991dc0248a628f9 e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +hello.txt.0.default.deflate 10 0422568b284c3e22bace9f6007e08dfa93a84d29849ed8c6fefda0d670b7dff3 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 +hello.txt.1.default.deflate 7 9c050feb4ff382803b4dd786f57d6b67089b784a8adf0ac969fe50086360ed91 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 +one.txt.0.default.deflate 6 0b96b18b4f7c1dcc466400c20c035f8542c8d19cecebe0e198c10be917b464a8 ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb +one.txt.1.default.deflate 3 59fced9a2ff83dabdd7055cf3abd6c12b802e6397b6fba5b8251cdf95d2bc991 ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb +random.bin.0.default.deflate 517 05ac6f07c56e47620e2f30d6589c342c89c5dd65c3448205133c2d7d32b0f171 13bd8ee11c001a4804bc2535d33b807e7e796b001f2970516dea564248968c9b +ray.txt.0.default.deflate 261 9aad2c0b40f39e77ff328909913a8a30ccc912cbeb1789e8a4911872994a24d5 2ac3f639ab3e378293c0afeaabd2a66b3c26e55b5bbf11b0445caa6cafef3f08 +ray.txt.1.default.deflate 9 680504f8e79d7996f54a528dc83f79ca2152f5417518c23abc653e30ee55e4d9 2ac3f639ab3e378293c0afeaabd2a66b3c26e55b5bbf11b0445caa6cafef3f08 +ray.txt.1.huffman.deflate 89 7f454fba93dd069c417af7ceb6d0a861a35aa36220aaa8cd4c97a48e3c010670 2ac3f639ab3e378293c0afeaabd2a66b3c26e55b5bbf11b0445caa6cafef3f08 +run.bin.0.default.deflate 305 8420f85c1ef6df5ef4880bf44702e1d3c29503003ec51934ea6efba0a5f42903 4daeb9ac8be203281aceb5f4511220333686abfde4d2ccd50a49cd156a2e8cf5 +run.bin.1.default.deflate 8 fe7245f833be968622f6703335db6a943a8133e9a339f0071c1e93c85095293b 4daeb9ac8be203281aceb5f4511220333686abfde4d2ccd50a49cd156a2e8cf5 +run.bin.1.huffman.deflate 50 a0964fe7749bb61fa0838a958b46f855edfacba70f4cb70cde3e8eb1735057bc 4daeb9ac8be203281aceb5f4511220333686abfde4d2ccd50a49cd156a2e8cf5 +run.bin.1.rle.deflate 6 3bba2a385b3654e69555cc490ca7424fc20581a4902313b3590fe11436b85875 4daeb9ac8be203281aceb5f4511220333686abfde4d2ccd50a49cd156a2e8cf5 +run.bin.6.default.deflate 7 2dba3cb21a95d3b30da70413762d502c0695dd809ab447611f81369c8014267b 4daeb9ac8be203281aceb5f4511220333686abfde4d2ccd50a49cd156a2e8cf5 +text.txt.0.default.deflate 1245 05c642c1593de59972d8504eb303e50eb5978067d9a87ce3f858720a8eb950f3 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.1.default.deflate 333 29e9689a4497c3c77a1726282e5bd36c45809d8bcc5613bfa40bedb316b513f2 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.1.huffman.deflate 696 58e06925957f0da674931a687ab2d15d7f5a673ee33bc02f58f277813ffd5f97 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.1.fixed.deflate 422 42702939510ae8d5f46e84898e2d07f9785f8b837737f5429c791b205caf2db0 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.6.default.deflate 327 49f1df9fc9698e839a4108b2385491a4dad1e3541ab3a66a9dde4a0a7d589e14 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.6.filtered.deflate 329 4874e86bde5f4912f704572f6eba8c9fe8c52f096d2097f1bc3b48aa17849b44 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 +text.txt.6.fixed.deflate 410 8a8deefb39c6ce4231e49721c4ea31faf5afa5c3f573d3ee1e66b13c16890322 2e7785f33261f8997216a0c236321d26614c906000e1cf35a356cd6d4a2fc0a3 diff --git a/@ether/poc/deflate/corpus/one.txt.0.default.deflate b/@ether/poc/deflate/corpus/one.txt.0.default.deflate new file mode 100644 index 000000000..632544906 Binary files /dev/null and b/@ether/poc/deflate/corpus/one.txt.0.default.deflate differ diff --git a/@ether/poc/deflate/corpus/one.txt.1.default.deflate b/@ether/poc/deflate/corpus/one.txt.1.default.deflate new file mode 100644 index 000000000..4fd9e830a Binary files /dev/null and b/@ether/poc/deflate/corpus/one.txt.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/random.bin.0.default.deflate b/@ether/poc/deflate/corpus/random.bin.0.default.deflate new file mode 100644 index 000000000..05527f6ec Binary files /dev/null and b/@ether/poc/deflate/corpus/random.bin.0.default.deflate differ diff --git a/@ether/poc/deflate/corpus/ray.txt.0.default.deflate b/@ether/poc/deflate/corpus/ray.txt.0.default.deflate new file mode 100644 index 000000000..d3b7f8a1e Binary files /dev/null and b/@ether/poc/deflate/corpus/ray.txt.0.default.deflate differ diff --git a/@ether/poc/deflate/corpus/ray.txt.1.default.deflate b/@ether/poc/deflate/corpus/ray.txt.1.default.deflate new file mode 100644 index 000000000..a60f65b98 Binary files /dev/null and b/@ether/poc/deflate/corpus/ray.txt.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/ray.txt.1.huffman.deflate b/@ether/poc/deflate/corpus/ray.txt.1.huffman.deflate new file mode 100644 index 000000000..295da8807 Binary files /dev/null and b/@ether/poc/deflate/corpus/ray.txt.1.huffman.deflate differ diff --git a/@ether/poc/deflate/corpus/run.bin.0.default.deflate b/@ether/poc/deflate/corpus/run.bin.0.default.deflate new file mode 100644 index 000000000..861c0c2d5 --- /dev/null +++ b/@ether/poc/deflate/corpus/run.bin.0.default.deflate @@ -0,0 +1 @@ +,ÓþAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \ No newline at end of file diff --git a/@ether/poc/deflate/corpus/run.bin.1.default.deflate b/@ether/poc/deflate/corpus/run.bin.1.default.deflate new file mode 100644 index 000000000..c4c0c1097 Binary files /dev/null and b/@ether/poc/deflate/corpus/run.bin.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/run.bin.1.huffman.deflate b/@ether/poc/deflate/corpus/run.bin.1.huffman.deflate new file mode 100644 index 000000000..6b3c6fe69 Binary files /dev/null and b/@ether/poc/deflate/corpus/run.bin.1.huffman.deflate differ diff --git a/@ether/poc/deflate/corpus/run.bin.1.rle.deflate b/@ether/poc/deflate/corpus/run.bin.1.rle.deflate new file mode 100644 index 000000000..c2e828b9c Binary files /dev/null and b/@ether/poc/deflate/corpus/run.bin.1.rle.deflate differ diff --git a/@ether/poc/deflate/corpus/run.bin.6.default.deflate b/@ether/poc/deflate/corpus/run.bin.6.default.deflate new file mode 100644 index 000000000..d0c5debac Binary files /dev/null and b/@ether/poc/deflate/corpus/run.bin.6.default.deflate differ diff --git a/@ether/poc/deflate/corpus/text.txt.0.default.deflate b/@ether/poc/deflate/corpus/text.txt.0.default.deflate new file mode 100644 index 000000000..44bb649fb --- /dev/null +++ b/@ether/poc/deflate/corpus/text.txt.0.default.deflate @@ -0,0 +1 @@ +Ø'ûA declaration of a format is its type, its parser and its writer at once. Read, it turns bytes into a value whose fields are the pieces of its header; written, it turns that value back into the same bytes. DEFLATE packs its fields least significant bit first, reads its Huffman codes most significant bit first, and lets a copy reach back into what it has already written, even into the bytes it is writing. A stored block holds its bytes as they are; a fixed block uses the codes the format fixes; a dynamic block carries its own codes, written as the lengths of its codes, themselves written with a code of their own. A declaration of a format is its type, its parser and its writer at once. Read, it turns bytes into a value whose fields are the pieces of its header; written, it turns that value back into the same bytes. DEFLATE packs its fields least significant bit first, reads its Huffman codes most significant bit first, and lets a copy reach back into what it has already written, even into the bytes it is writing. A stored block holds its bytes as they are; a fixed block uses the codes the format fixes; a dynamic block carries its own codes, written as the lengths of its codes, themselves written with a code of their own. \ No newline at end of file diff --git a/@ether/poc/deflate/corpus/text.txt.1.default.deflate b/@ether/poc/deflate/corpus/text.txt.1.default.deflate new file mode 100644 index 000000000..00753e96c Binary files /dev/null and b/@ether/poc/deflate/corpus/text.txt.1.default.deflate differ diff --git a/@ether/poc/deflate/corpus/text.txt.1.fixed.deflate b/@ether/poc/deflate/corpus/text.txt.1.fixed.deflate new file mode 100644 index 000000000..fa1fde054 Binary files /dev/null and b/@ether/poc/deflate/corpus/text.txt.1.fixed.deflate differ diff --git a/@ether/poc/deflate/corpus/text.txt.1.huffman.deflate b/@ether/poc/deflate/corpus/text.txt.1.huffman.deflate new file mode 100644 index 000000000..7ffac232b --- /dev/null +++ b/@ether/poc/deflate/corpus/text.txt.1.huffman.deflate @@ -0,0 +1,3 @@ +ÁAn;EÑ­Ü4¼� |ddÕdQ,¨E +¬'µ{÷ÿœ/ª—Ö)æ`6Œ6×ÃD$¡D×Ó7BÉÓVúÂF%”œ+ä sÿà¯[Ý¡×É~É“šo;^ÎÙg:-ü¨‰-GÝy†Of#”t·êë“s…äc#„^k$ê&Þv¼œÝÊ�š¨;ig¿äùÁß¿þ|ýûæiåž„’~ÔäpK‘qÑ¢Ø{ˆ+µ±ÜjJ~¿Z{Ø ÌêÉc¦È¸�hQlˆ=D‹•Ú°Q9\‰Qæób¹•ÎnåN MÎn"D·ÄŽåV/Î’� û †&êÎ~É“‘œ+ãöÁ©¹¼²³Üéó¨I(Ù/yb‰º_ØòOŒ?^Ù�Yî¼Òu§Ìê‰ºÓæz˜hñãù‰Q¯a�(ìÇ,wŠ­ž„’yʬžç +É–¨;‡�›z2¡¤Ì깡î�ôãíɹBòÁêeVg6Ô=ó|Q½¶L1³a´¹&" %ºž¾Jž¶Ò6*¡ä\!_˜˜£øÝêF½ÖHöKžÄÐÄxÛñrÎ>ÓiáGMl9êÎ3¼x2¡¤»U_Ÿœ+$!ôZ#Q7ñ¶ãåìVîÄÐDÝI{8û%Ïþûþõçëß7O+÷$”´ð£&‡[ŠŒÛˆņØC´X©�åV“PòûÕÚÃeVO3EÆmD‹bCì!Z¬Ô†�ÊáJŒ2ŸË­tv+wbhrv!º%v,·zq®�|løÛ14QwöKž„ˆä\¡·¾HÍå•ý˜åNŸGMBÉ~ÉKÔý–b´øñÊ~Ìr畞¨;eVOÔ�6×ÃD‹ÏOŒz {Da?f¹Sl­ð$”ÌsPfõÜ8WH>°DÝ9|ÜÔ“Ù%eVÏ u¤oOÎ’ÎPÇ(³:³¡î±˜çøà \ No newline at end of file diff --git a/@ether/poc/deflate/corpus/text.txt.6.default.deflate b/@ether/poc/deflate/corpus/text.txt.6.default.deflate new file mode 100644 index 000000000..0441ce345 Binary files /dev/null and b/@ether/poc/deflate/corpus/text.txt.6.default.deflate differ diff --git a/@ether/poc/deflate/corpus/text.txt.6.filtered.deflate b/@ether/poc/deflate/corpus/text.txt.6.filtered.deflate new file mode 100644 index 000000000..45ebf22a7 Binary files /dev/null and b/@ether/poc/deflate/corpus/text.txt.6.filtered.deflate differ diff --git a/@ether/poc/deflate/corpus/text.txt.6.fixed.deflate b/@ether/poc/deflate/corpus/text.txt.6.fixed.deflate new file mode 100644 index 000000000..abe59bf73 Binary files /dev/null and b/@ether/poc/deflate/corpus/text.txt.6.fixed.deflate differ diff --git a/@ether/poc/deflate/dp0.ray b/@ether/poc/deflate/dp0.ray new file mode 100644 index 000000000..60b4b7868 --- /dev/null +++ b/@ether/poc/deflate/dp0.ray @@ -0,0 +1,44 @@ +// DP0: each feature `Deflate.ray` uses, on a toy format of a few bits. + +mark ^keyword := global + +Pair := class (high: Binaryâ‚‚, low: <-Binaryâ‚‚) => { } +unless Pair.bits_read("1001").high == 2 { INFO@mark `DP0.1a a fixed-width field does not read most significant first` } +unless Pair.bits_read("1001").low == 2 { INFO@mark `DP0.1b a reversed field does not read least significant first` } + +Kind := class (kind: Binaryâ‚‚{< 3}) => { } +unless Kind.bits_read("10").kind == 2 { INFO@mark `DP0.2a a narrowed field does not read what holds` } +if Kind.bits_read("11") { INFO@mark `DP0.2b a narrowed field reads what does not hold` } + +Either := class (items: ((small: Binaryâ‚‚{< 2}) | (Binaryâ‚‚{== 3}, big: Binary₃))[], Binaryâ‚‚{== 2}) => { } +either := Either.bits_read("0111101" + "10") +unless either.items.count == 2 { INFO@mark `DP0.3a alternatives in a list do not read each element` } +unless either.items.first.small == 1 { INFO@mark `DP0.3b the first alternative's field is not read` } +unless either.items.last.big == 5 { INFO@mark `DP0.3c the second alternative's field is not read` } + +Sized := class (size: Binaryâ‚‚, values: (Binaryâ‚‚)[]{length == size}) => { } +sized := Sized.bits_read("10" + "0111") +unless sized.values == [1, 3] { INFO@mark `DP0.4a a list as long as an earlier field does not read that many` } +if Sized.bits_read("10" + "01") { INFO@mark `DP0.4b a list shorter than its length is read` } + +Tagged := class (tag: Binaryâ‚�, (wide: Binaryâ‚„) if tag == 1, (narrow: Binaryâ‚‚) if tag == 0) => { } +unless Tagged.bits_read("11010").wide == 10 { INFO@mark `DP0.5a a piece whose condition holds is not read` } +unless Tagged.bits_read("010").narrow == 2 { INFO@mark `DP0.5b a piece whose condition does not hold is read` } +if Tagged.bits_read("010").wide !== None { INFO@mark `DP0.5c a piece not read has a value` } + +Width := class (bits: Binaryâ‚�) => { + width => bits + 1 +} +Inner := class (value: Binary{length == width.width}) => { } +Outer := class (width: Width, inner: Inner) => { } +unless Outer.bits_read("1" + "10").inner.value == 2 { INFO@mark `DP0.6 a class given a value read before it does not read with it` } + +Aligned := class (head: Binary₃, padding: Binary{(length < 8) && (((at + length) % 8) == 0)}, byte: Byte) => { } +aligned := Aligned.bits_read("101" + "00000" + "00000110") +unless aligned.byte == 6 { INFO@mark `DP0.7 the piece up to the byte boundary does not end there` } + +Counted := class (count: Binaryâ‚‚ = values.count, values: (Binaryâ‚‚)[]{length == count}) => { } +unless Counted(values: [1, 2]).binary == "10" + "0110" { INFO@mark `DP0.8 a default is not computed when a value is written` } + +unless Pair(high: 2, low: 2).binary == "1001" { INFO@mark `DP0.9a a value is not written back to its bits` } +unless Either.bits_read("0111101" + "10").binary == "0111101" + "10" { INFO@mark `DP0.9b a value read is not written back to the same bits` } diff --git a/@ether/poc/deflate/dp2.ray b/@ether/poc/deflate/dp2.ray new file mode 100644 index 000000000..ab883e4f4 --- /dev/null +++ b/@ether/poc/deflate/dp2.ray @@ -0,0 +1,10 @@ +// DP2: the RFC's own cases, the claims of `$/deflate/tests/deflate.ray` DF1 to DF6. + +mark ^keyword := global + +unless Deflate.Huffman([3, 3, 3, 3, 3, 2, 4, 4]).codes.sort_by((code) => code.symbol).map((code) => code.bits) == [0b010, 0b011, 0b100, 0b101, 0b110, 0b00, 0b1110, 0b1111] { INFO@mark `DF1 the code lengths of section 3.2.2's example do not give its codes` } +unless (Deflate.fixed_literals.bits(0) == 0b00110000) && (Deflate.fixed_literals.bits(144) == 0b110010000) && (Deflate.fixed_literals.bits(256) == 0b0000000) { INFO@mark `DF2 the fixed literal codes are not those of section 3.2.6` } +unless Deflate.inflated([0x01, 0x05, 0x00, 0xfa, 0xff, "hello".bytes].flatten) == "hello".bytes { INFO@mark `DF3 a stored block does not read its bytes` } +unless Deflate.inflated([0x03, 0x00]).empty { INFO@mark `DF4 an empty fixed block is not empty` } +unless Deflate.inflated([0x4b, 0x04, 0x00]) == "a".bytes { INFO@mark `DF5 a literal with the fixed codes is not read` } +unless Deflate.inflated([0x4b, 0x84, 0x03, 0x00]) == "aaaaaaaaaa".bytes { INFO@mark `DF6 a back-reference overlapping what it writes is not copied` } diff --git a/@ether/poc/deflate/dp5.ray b/@ether/poc/deflate/dp5.ray new file mode 100644 index 000000000..c1348fdcd --- /dev/null +++ b/@ether/poc/deflate/dp5.ray @@ -0,0 +1,7 @@ +// DP5: data Ray writes from nothing, the claims of `$/deflate/tests/deflate.ray` DF7 and DF8. + +mark ^keyword := global + +repeated := ("ray " * 64).bytes +unless Deflate.inflated(Deflate.deflated(repeated)) == repeated { INFO@mark `DF7 written bytes do not read back` } +unless Deflate.deflated(repeated).count < repeated.count { INFO@mark `DF8 repeated bytes are not written shorter` } diff --git a/@ether/poc/deflate/inputs/empty.bin b/@ether/poc/deflate/inputs/empty.bin new file mode 100644 index 000000000..e69de29bb diff --git a/@ether/poc/deflate/inputs/hello.txt b/@ether/poc/deflate/inputs/hello.txt new file mode 100644 index 000000000..b6fc4c620 --- /dev/null +++ b/@ether/poc/deflate/inputs/hello.txt @@ -0,0 +1 @@ +hello \ No newline at end of file diff --git a/@ether/poc/deflate/inputs/one.txt b/@ether/poc/deflate/inputs/one.txt new file mode 100644 index 000000000..2e65efe2a --- /dev/null +++ b/@ether/poc/deflate/inputs/one.txt @@ -0,0 +1 @@ +a \ No newline at end of file diff --git a/@ether/poc/deflate/inputs/random.bin b/@ether/poc/deflate/inputs/random.bin new file mode 100644 index 000000000..f606f7258 Binary files /dev/null and b/@ether/poc/deflate/inputs/random.bin differ diff --git a/@ether/poc/deflate/inputs/ray.txt b/@ether/poc/deflate/inputs/ray.txt new file mode 100644 index 000000000..46033ae72 --- /dev/null +++ b/@ether/poc/deflate/inputs/ray.txt @@ -0,0 +1 @@ +ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray ray \ No newline at end of file diff --git a/@ether/poc/deflate/inputs/run.bin b/@ether/poc/deflate/inputs/run.bin new file mode 100644 index 000000000..1de29f83c --- /dev/null +++ b/@ether/poc/deflate/inputs/run.bin @@ -0,0 +1 @@ +AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA \ No newline at end of file diff --git a/@ether/poc/deflate/inputs/text.txt b/@ether/poc/deflate/inputs/text.txt new file mode 100644 index 000000000..54ef68490 --- /dev/null +++ b/@ether/poc/deflate/inputs/text.txt @@ -0,0 +1 @@ +A declaration of a format is its type, its parser and its writer at once. Read, it turns bytes into a value whose fields are the pieces of its header; written, it turns that value back into the same bytes. DEFLATE packs its fields least significant bit first, reads its Huffman codes most significant bit first, and lets a copy reach back into what it has already written, even into the bytes it is writing. A stored block holds its bytes as they are; a fixed block uses the codes the format fixes; a dynamic block carries its own codes, written as the lengths of its codes, themselves written with a code of their own. A declaration of a format is its type, its parser and its writer at once. Read, it turns bytes into a value whose fields are the pieces of its header; written, it turns that value back into the same bytes. DEFLATE packs its fields least significant bit first, reads its Huffman codes most significant bit first, and lets a copy reach back into what it has already written, even into the bytes it is writing. A stored block holds its bytes as they are; a fixed block uses the codes the format fixes; a dynamic block carries its own codes, written as the lengths of its codes, themselves written with a code of their own. \ No newline at end of file diff --git a/@ether/poc/deflate/make.py b/@ether/poc/deflate/make.py new file mode 100644 index 000000000..040bdd462 --- /dev/null +++ b/@ether/poc/deflate/make.py @@ -0,0 +1,111 @@ +import hashlib +import os +import sys +import zlib + +here = os.path.dirname(os.path.abspath(__file__)) +inputs = os.path.join(here, 'inputs') +corpus = os.path.join(here, 'corpus') + +LEVELS = [0, 1, 6, 9] +STRATEGIES = { + 'default': zlib.Z_DEFAULT_STRATEGY, + 'filtered': zlib.Z_FILTERED, + 'huffman': zlib.Z_HUFFMAN_ONLY, + 'rle': zlib.Z_RLE, + 'fixed': zlib.Z_FIXED, +} + + +def raw(data, level, strategy): + made = zlib.compressobj(level, zlib.DEFLATED, -15, 9, strategy) + return made.compress(data) + made.flush() + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def build(): + os.makedirs(corpus, exist_ok=True) + lines, seen = [], set() + for name in sorted(os.listdir(inputs)): + data = open(os.path.join(inputs, name), 'rb').read() + for level in LEVELS: + for strategy, value in STRATEGIES.items(): + stream = raw(data, level, value) + if stream in seen: + continue + seen.add(stream) + assert zlib.decompress(stream, -15) == data + file = f'{name}.{level}.{strategy}.deflate' + open(os.path.join(corpus, file), 'wb').write(stream) + lines.append(f'{file} {len(stream)} {sha(stream)} {sha(data)}') + return '\n'.join(lines) + '\n' + + +def stream(bits): + bits += '0' * (-len(bits) % 8) + return bytes(int(bits[at:at + 8][::-1], 2) for at in range(0, len(bits), 8)) + + +def lsb(value, width): + return format(value, f'0{width}b')[::-1] + + +def code_lengths(sequence): + # a dynamic block with a complete code length code (symbols 0 to 12 four bits, 13 to 18 five), then `sequence` + order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15] + lengths = {symbol: 4 if symbol < 13 else 5 for symbol in range(19)} + codes, code = {}, 0 + for width in range(1, 6): + for symbol in range(19): + if lengths[symbol] == width: + codes[symbol] = format(code, f'0{width}b') + code += 1 + code *= 2 + return '1' + lsb(2, 2) + lsb(0, 5) + lsb(0, 5) + lsb(15, 4) + ''.join(lsb(lengths[s], 3) for s in order) + ''.join(codes[s] + extra for s, extra in sequence) + + +# Each stream zlib rejects, with the bit where reading it must stop ('-': it reads, and what it means does not hold). +BAD = { + 'btype3': ('1' + '11', 3), + 'nlen': ('1' + lsb(0, 2) + '00000' + lsb(5, 16) + lsb(0xfefa, 16) + ''.join(lsb(b, 8) for b in b'hello'), 40), + 'truncated': ('1' + lsb(1, 2) + '00110', 3), + 'fixed286': ('1' + lsb(1, 2) + '11000110', 11), + 'far': ('1' + lsb(1, 2) + '0000001' + '00000' + '0000000', '-'), + 'repeat': (code_lengths([(16, lsb(0, 2))]), '-'), + 'oversubscribed': ('1' + lsb(2, 2) + lsb(0, 5) + lsb(0, 5) + lsb(15, 4) + lsb(1, 3) * 19, '-'), +} + + +def bad(): + folder = os.path.join(here, 'bad') + os.makedirs(folder, exist_ok=True) + lines = [] + for name, (bits, stop) in BAD.items(): + data = stream(bits) + try: + zlib.decompress(data, -15) + sys.exit(f'zlib does not reject {name}') + except zlib.error as error: + reason = str(error).split(': ', 1)[-1] + open(os.path.join(folder, name + '.deflate'), 'wb').write(data) + lines.append(f'{name}.deflate {stop} {reason}') + open(os.path.join(folder, 'manifest.txt'), 'w').write('\n'.join(lines) + '\n') + print(f'wrote {len(lines)} streams zlib rejects') + + +if __name__ == '__main__': + if len(sys.argv) > 1 and sys.argv[1] == '--bad': + bad() + sys.exit() + manifest = build() + path = os.path.join(corpus, 'manifest.txt') + if len(sys.argv) > 1 and sys.argv[1] == '--check': + if open(path).read() != manifest: + sys.exit('the corpus zlib makes now differs from manifest.txt') + print(f'DP1 {manifest.count(chr(10))} streams match manifest.txt; zlib inflates each to its input') + else: + open(path, 'w').write(manifest) + print(f'wrote {manifest.count(chr(10))} streams') diff --git a/@ether/poc/deflate/run.mts b/@ether/poc/deflate/run.mts new file mode 100644 index 000000000..d5c9ff820 --- /dev/null +++ b/@ether/poc/deflate/run.mts @@ -0,0 +1,21 @@ +// The strict claim runner: each `unless`/`if … { INFO@mark … }` claim holds only when its condition answers the `true` node +// (`false` or `None` for `if`), so a condition left unread fails. +const { booted, Program } = await import('./boot.mts'); +const { program, statements } = await booted(); +const yes = program.run('true', { node: program.global }), no = program.run('false', { node: program.global }), none = program.run('None', { node: program.global }); +const shown = (value: unknown) => value instanceof Program.Node ? 'node(' + value.rules.slice(0, 8).map((rule: any) => rule.head).join(', ') + ')' : JSON.stringify(value); +let failed = 0; +for (const file of process.argv.slice(2)) for (const statement of statements(file)) { + const claim = /^(unless|if) (.*) \{ INFO@mark `([A-Za-z]+[0-9][0-9A-Za-z.]* [^`]*)` \}$/s.exec(statement.trim()); + if (process.env.RD) { const c = program.candidates(statement.trim(), program.global, 0); console.log('>', statement.trim()); for (const r of program.readings(statement.trim(), c, false).slice(-6)) console.log(' ', r.rule.head, JSON.stringify(r.spans), r.at); } + let value: unknown; + program.steps = 0; + try { value = program.run(claim ? claim[2] : statement, { node: program.global }); } catch (error: any) { value = 'threw ' + error?.message; } + if (claim) { + const held = claim[1] === 'unless' ? value === yes : value === no || value === none; + if (!held) failed++; + console.log(held ? 'ok ' : 'FAIL', claim[3], held ? '' : '(answered ' + shown(value) + ')'); + } + else if (process.env.SHOW) console.log(' ', statement.split('\n')[0], '=', shown(value)); +} +process.exitCode = failed ? 1 : 0; diff --git a/@ether/poc/deflate/run.sh b/@ether/poc/deflate/run.sh new file mode 100755 index 000000000..dd7758582 --- /dev/null +++ b/@ether/poc/deflate/run.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +ether="$(cd "$here/../.." && pwd)" +ray() { (ulimit -s unlimited; cd "$ether/v0.ts" && ETHER="$ether" KINDS_AFTER=1 LOAD='$/deflate/Deflate.ray' STEPS=80000000 node --max-old-space-size=12000 --stack-size=60000 --import tsx "$here/$1" "${@:2}" 2>/dev/null); } +each() { + local failed=0 + for name in $(cut -d' ' -f1 "$here/corpus/manifest.txt"); do ONLY="$name" ray corpus.mts "$1" | grep -E '^(ok|FAIL)' || failed=1; done + [ "$failed" = 0 ] && echo "$2" || { echo "some failed"; exit 1; } +} +case "${1:-}" in + DP0) ray run.mts "$here/dp0.ray" ;; + DP1) python3 "$here/make.py" --check ;; + DP2) ray run.mts "$here/dp2.ray" ;; + DP3) each read "DP3 every corpus stream read to what zlib inflates it to" ;; + DP4) each rewrite "DP4 every corpus stream written back byte for byte" ;; + DP5) + ray run.mts "$here/dp5.ray" + failed=0 + for name in $(ls "$here/inputs"); do ONLY="$name" ray corpus.mts write | grep -E '^(ok|FAIL)' || failed=1; done + [ "$failed" = 0 ] && echo "DP5 every input written so zlib, and Ray, read it back" || { echo "some failed"; exit 1; } + ;; + DP6) ray corpus.mts reject ;; + *) echo "usage: run.sh DP0|DP1|DP2|DP3|DP4|DP5|DP6" >&2; exit 2 ;; +esac diff --git a/@ether/ray/.entrypoint.ray2 b/@ether/ray/.entrypoint.ray2 index 37c8fd9ef..5dbcda66e 100644 --- a/@ether/ray/.entrypoint.ray2 +++ b/@ether/ray/.entrypoint.ray2 @@ -154,7 +154,7 @@ Pattern := { narrowing := { } }).narrowing) -// What a value answers to `?`: anything is true, but `None` and `false`. +// What a value answers to `?`: anything is true, but `None` and `false`. (`!x`, not x; `!= y` is not one: the next reading.) ? {yes} : {no} => {yes} None := { @@ -171,6 +171,7 @@ false := { } true := { } !{x} => + (goto .) if "{x}" begins "=" {x} ? false : true {a} || {b} => {a} ? {a} : {b} @@ -205,29 +206,20 @@ unless {condition} {{taken}} => taken\ {taken} passed\ -// (a chain, `if … {} elsif … {} else {}`: its condition ends at the nearest body) -nearest if {condition} {{taken}} {chain} => - {condition} ? (goto taken) : (goto otherwise) - taken\ - {taken} - goto passed - otherwise\ - {chain} - passed\ nearest elsif {condition} {{taken}} => {condition} ? (goto taken) : (goto passed) taken\ {taken} passed\ -nearest elsif {condition} {{taken}} {chain} => +nearest elsif {condition} {{taken}} else {{otherwise}} => {condition} ? (goto taken) : (goto otherwise) taken\ {taken} goto passed otherwise\ - {chain} + {otherwise} passed\ -nearest elsif {condition} {{taken}} else {{otherwise}} => +if {condition} {{taken}} else {{otherwise}} => {condition} ? (goto taken) : (goto otherwise) taken\ {taken} @@ -235,13 +227,24 @@ nearest elsif {condition} {{taken}} else {{otherwise}} => otherwise\ {otherwise} passed\ -if {condition} {{taken}} else {{otherwise}} => +// (a chain, `if … {} elsif … {} else {}`: its condition ends at the nearest body; the chain begins with `elsif`, so a +// condition with an operator in it, `if a > b { … }`, is not read as a body `>`; defined after `else`, so a chain is not +// read as an `else` whose condition holds a body) +nearest if {condition} {{taken}} elsif {{chain}} => {condition} ? (goto taken) : (goto otherwise) taken\ {taken} goto passed otherwise\ - {otherwise} + elsif {chain} + passed\ +nearest elsif {condition} {{taken}} elsif {{chain}} => + {condition} ? (goto taken) : (goto otherwise) + taken\ + {taken} + goto passed + otherwise\ + elsif {chain} passed\ // Loops: `break` goes to the loop's end, `continue` to its start. @@ -644,16 +647,28 @@ class:{ }{parent} {{block}} => class: {parent} (arguments = None) => { {block} } -// (the block read once for the class; again for each instance, only what is not a definition (`instanced`)) +// (the block read once for the class; again for each instance, only what is not a definition (`instanced`)) (a header of bits, +// one with pieces that are not parameters, has its maker made by the host, `instance_defined`) nearest class:{ }{parent}{ }({fields}) => {{block}} => (made class: {parent} { {block} + (goto of-bits) unless plain { + {fields} + } instance := ({fields}) => of := instance (here of) instanced { {block} } of := instance + goto made-plainly + of-bits\ + instance_defined { + {fields} + } { + {block} + } + made-plainly\ // (what is added to the maker, `X &+= { … }`, is added to the class) instance &+= { {`&+=`} {{added}} => @@ -667,10 +682,52 @@ class {{block}} => class: Node { {block} } +// (a header written without `=>` before its block, the form the library writes, `class (h) { … }`; or without brackets, or +// without a block, `class byte: Byte`: the same class) (after the one above, so they read a header it would take as code) +class{ }{name}:{ }{type} => + class: Node ({name}: {type}) => { } +class{ }{name}:{ }{type} {{block}} => + class: Node ({name}: {type}) => { + {block} + } +class{ }({fields}) => + class: Node ({fields}) => { } +class{ }({fields}) {{block}} => + class: Node ({fields}) => { + {block} + } +class<{{given}}>{ }({fields}) => + class: Node ({given}, {fields}) => { } +class<{{given}}>{ }({fields}) {{block}} => + class: Node ({given}, {fields}) => { + {block} + } +// (written over lines: `(` and `)` each with the fields on the lines between) +class{ }({ }{fields}{ }) => + class: Node ({fields}) => { } +class{ }({ }{fields}{ }) {{block}} => + class: Node ({fields}) => { + {block} + } +class<{{given}}>{ }({ }{fields}{ }) => + class: Node ({given}, {fields}) => { } +class<{{given}}>{ }({ }{fields}{ }) {{block}} => + class: Node ({given}, {fields}) => { + {block} + } class{ }({fields}) => {{block}} => class: Node ({fields}) => { {block} } +// (one given values before its fields, `class (…)`, `C(…)`: those are its first fields) +class<{{given}}>{ }({fields}) => {{block}} => + class: Node ({given}, {fields}) => { + {block} + } +{{name}}{ }:={ }class<{{given}}>{ }({fields}) => {{block}} => + {name} := (class: Node ({given}, {fields}) => { + {block} + }) // What a value is: a Node (anything is; the outermost node); the value itself; an instance of the class (or of one after it, // `class:`) it was made by; one of a superposition's components; a narrowing that holds of it; a member of an enumeration. @@ -759,11 +816,11 @@ goto declaring goto declaring static {{statement}} -// `x as T`: x, when it is a T; else what T makes of it (`T.from(x)`; none, by default). +// `x as T`: x, when it is a T; else what T makes of it (`T.from(x)`; none, by default); else bits read by T's header. from (x) => None as {type} => - (. is {type}) ? . : {type}.from(.) + (. is {type}) ? . : (({type}.from(.)) ?? ({type}.bits_read(.))) // What a value holds under a key: its entries (`keyed`: `key`, `value`), a Ray; none until one is given. keyed := None @@ -996,6 +1053,93 @@ Iterable &+= { .append(other) } . + // (the same values in the same order: each the other's, or a list alike; anything not a list, not the same) (an operator + // is read where a member was read on, so a list's `==` is the host's, which asks this) + alike (other) => + (goto different) unless (other !== None) && other.listing + at := .head + there := other.head + while at && there { + (goto different) unless (at.value === there.value) || (at.value.listing && at.value.alike(there.value)) + at = at.next + there = there.next + } + (goto different) if at || there + return true + different\ + false + // (each value in the order of what `key` gives it, those it gives alike in the order they were) + sort_by (key) => + made := Listing.new + .for((x) => made.inserted(x, key)) + made + inserted (value, key) => + at := .tail + while at && (key(value) < key(at.value)) { + at = at.previous + } + link := { + value := value + next := None + previous := None + } + if at { + link.previous := at + link.next := at.next + (at.next.previous := link) if at.next + at.next := link + } else { + link.next := .head + (.head.previous := link) if .head + .head := link + } + (.tail := link) unless link.next + . + // (its values again, `count` times: `xs * n`) + repeated (count) => + made := Listing.new + left := count + while left > 0 { + made.joined(.) + left = left - 1 + } + made + // (its values from `from` up to `to` (not it), counted from 0) + slice (from, to) => + made := Listing.new + at := .head + index := 0 + while at && (index < to) { + (made.append(at.value)) if index >= from + at = at.next + index = index + 1 + } + made + // (its values written one after another, `separator` between each two) + join (separator) => + at := .head + made := at ? at.value : "" + at = at ? at.next : None + while at { + made = made + separator + at.value + at = at.next + } + made + // (where a value first is, counted from 0; none, None) + index_of (value) => + at := .head + index := 0 + while at { + return index if at.value === value + at = at.next + index = index + 1 + } + None + // (the values of the lists in it, in order; a value that is not a list, itself) + flatten => + made := Listing.new + .for((x) => made.joined(x)) + made } } Listing := Iterable.interior.Listing diff --git a/@ether/spec/Deflate.md b/@ether/spec/Deflate.md new file mode 100644 index 000000000..44541e2ce --- /dev/null +++ b/@ether/spec/Deflate.md @@ -0,0 +1,301 @@ +# DEFLATE proof: one declaration reads and writes a real format + +The claim under test: a Ray class declaration of a format is its type, its parser and its writer at once, in both +directions. `$/deflate/Deflate.ray` (136 lines) declares RFC 1951 that way. Its class headers read a stream, and the +defaults on their fields (`size: <-Binaryâ‚�₆ = bytes.count`) write one. This POC makes that claim pass or fail on bytes +made by zlib, the format's reference implementation. + +Every item is **Q** (needs your decision) unless it is under **Decided**. IDs `DP…`. + +Why DEFLATE: + +- **It is the hard case for a declarative format.** Fields are bits, packed least significant bit first. The Huffman codes + that decode the data are themselves read from the stream before it (`Data`). Copies reach back + across blocks and may overlap what they write. The zlib and gzip wrappers end in checksums over all of the data. +- **The closest tools do not declare it.** Kaitai Struct (`process: zlib`) and Construct (`Compressed(…, "zlib")`) hand + DEFLATE to a zlib library. DP8 checks this and compares. +- **It is on the path.** `$.png` reads through `$/zlib` and `$/deflate` (Frontend.md), and machine code, the next binary + format (DP9, and C1 of `Interop.md` on `proposal/interop-poc`), is read by the same mechanism. + +--- + +## Principles + +- **One declaration.** Nothing in the POC reads or writes DEFLATE except `$/deflate/Deflate.ray` (and `$/zlib/Zlib.ray`, + `$/gzip/Gzip.ray` in DP7). A wrong declaration is fixed there, one commit per fix. There is no second reader, no + writer beside the declaration, and no TS decoder. +- **The engine is language3** (`v0.ts/src/language3.ts` with `ray/.entrypoint.ray2`), run through a strict claim runner + like `poc/interop/run.mts`: a claim holds only when its condition answers the `true` node, so a condition the engine + leaves unread fails. A step the engine cannot do stops, and the gap is recorded under **Engine gaps** with its probe. +- **zlib is the oracle.** python3's `zlib` makes the corpus and checks what Ray writes. A step passes on a `diff` or + `cmp`, never on prose. + +## Scope + +- **In:** raw RFC 1951 streams with all three block kinds (stored, fixed, dynamic); reading, writing back what was read, + writing new data, rejecting malformed streams; the zlib (RFC 1950) and gzip (RFC 1952) wrappers in DP7. +- **Out:** compression ratio (the writer has to be correct, not good; `parsed` is a brute-force LZ77 and stays one); + speed as a gate (it is measured in DP8); preset dictionaries; gzip files of more than one member beyond a single + claim. + +## Layout + +All POC files live in `@ether/poc/deflate/`: + +| File | Role | +|---|---| +| `README.md` | The walkthrough: one section per step, in order | +| `run.sh` | `./run.sh ` runs one step, e.g. `./run.sh DP4` | +| `run.mts` | The strict claim runner; boots language3, the core library and `$/deflate` | +| `make.py` | Builds the corpus with python3's `zlib` | +| `inputs/` | Small pinned inputs, committed | +| `corpus/` | The streams `make.py` writes, committed with `manifest.txt` so the corpus does not move with the zlib version | +| `bad/` | Malformed streams for DP6, each with the bit offset where reading must stop | +| `dp0.ray` … `dp7.ray` | Claims per step | +| `out/` | What Ray reads and writes; ignored by git | + +Each step in `README.md` has the five parts of Interop.md IOP2 (goal, what happens, why it matters, command, pass), and +each step is one commit. + +## Baseline + +Measured 2026-10-10 on main (`373672c9`), and on the `proposal/interop-poc` kernel with the same result. With +`Deflate.ray` loaded through the strict runner: + +- DF1 (the Huffman example of RFC 1951 §3.2.2) answers `undefined`. +- DF3 (a stored block) throws `Maximum call stack size exceeded` at node's default stack. +- With `--stack-size=20000` node dies with a segmentation fault. + +No DF claim passes. DP0 starts here. + +## Steps + +### DP0 Engine probes + +- **Goal.** Know which features of the declaration the engine reads, one at a time. +- **What happens.** `dp0.ray` has one small claim per feature `Deflate.ray` uses, each on a toy format of a few bits, not + on DEFLATE: + - DP0.1 a fixed-width bit field `Binaryâ‚‚`, and the same field reversed, `<-Binaryâ‚‚` + - DP0.2 a narrowed field in a header, `Binaryâ‚‚{< 3}` + - DP0.3 alternatives in a header, `(a: …) | (b: …)` + - DP0.4 repetition `(…)[]`, with a length tied to an earlier field, `{length == size}` + - DP0.5 a conditional piece, `(x: T) if kind == 0` + - DP0.6 a class parameter read from earlier data, `class`, used as `Data` + - DP0.7 the byte boundary piece, `Binary{length < 8 && (at + length) % 8 == 0}` + - DP0.8 a default that computes a field when writing, `size: <-Binaryâ‚�₆ = bytes.count` + - DP0.9 a value written back to bits, `x as Binary` + - DP0.10 `Language.read` and `Language.write` through `level` and `written` +- **Why it matters.** The declaration uses all ten at once, so a failure in DEFLATE does not say which one is missing. +- **Pass.** `./run.sh DP0` prints `ok` for DP0.1 to DP0.10. Each probe that fails is entered under Engine gaps before + work on it starts. + +### DP1 Oracle and corpus + +- **Goal.** Fix the streams every later step is checked against. +- **What happens.** `make.py` compresses each file in `inputs/` with python3's `zlib.compressobj` as raw DEFLATE + (`wbits=-15`), at levels 0, 1, 6 and 9 and with the strategies default, `Z_FILTERED`, `Z_HUFFMAN_ONLY`, `Z_RLE` and + `Z_FIXED`, drops identical streams, and writes `corpus/...deflate` and `manifest.txt` (name, + size, SHA-256 of the stream and of its inflated bytes). It also reports coverage: which block kinds, length codes + (257 to 285) and distance codes (0 to 29) occur. +- **Inputs.** Empty; one byte; `hello`; `ray ` 64 times (DF7); 300 equal bytes (length 258, overlapping copies); a few + KB of English text (dynamic blocks); a few KB of random bytes (stored blocks). Large inputs, such as a copy that + reaches 32768 back or a stored block of 65535 bytes, go in `corpus/large/`, used only in DP8 (DQ1). +- **Why it matters.** Streams Ray did not make are the only fair test of a reader. zlib's choices (block boundaries, + code-length runs, `HCLEN` below 15) are ones the declaration never chose. +- **Pass.** `./run.sh DP1` rebuilds the corpus with python3's `zlib` and finds it equal to `manifest.txt`, and zlib inflates + each stream to its input. Which block kinds and codes the corpus holds is what Ray reads in DP3 (a second reader to count + them would break DP0's one declaration); the small tier holds stored, fixed and dynamic blocks. + +### DP2 Read the RFC's own cases + +- **Goal.** The examples the RFC gives read as the RFC says. +- **What happens.** The existing claims in `$/deflate/tests/deflate.ray`: DF1 (the code lengths of §3.2.2 give its + codes), DF2 (the fixed codes of §3.2.6), DF3 (a stored block), DF4 (an empty fixed block), DF5 (a literal with the + fixed codes), DF6 (a copy that overlaps what it writes). +- **Pass.** `./run.sh DP2` prints `ok` for DF1 to DF6 on the strict runner. + +### DP3 Read the corpus + +- **Goal.** Every stream zlib made reads to the bytes zlib inflates it to. +- **What happens.** For each corpus stream the runner reads `Deflate.read(bytes)` and writes the result to + `out/read/`. +- **Why it matters.** This is the first contact with dynamic Huffman tables, code-length runs (16, 17, 18) and copies + across blocks. +- **Pass.** `./run.sh DP3`: for every stream, `out/read/` has the inflated SHA-256 in `manifest.txt`. + +### DP4 Write back what was read + +- **Goal.** A stream read into Ray is written back byte for byte. +- **What happens.** For each corpus stream the runner reads a `Deflate.Stream`, writes that same value as bytes + (`stream as Byte[]`) to `out/rewritten/`, and `cmp`s it with the original. +- **Why it matters.** This is the claim. The same declaration runs the other way, with no writer code. A `Stream` holds + every choice zlib made (block boundaries and kinds, code lengths and their run-length entries, every literal and + copy), so writing it has to give zlib's bits back. A mismatch means the declaration drops information. +- **Known risk.** The alignment piece in `Stored` and the final padding in `Stream` are unnamed, so they are written as + zeros. zlib writes zeros, so the corpus passes; a valid stream with other padding bits would not (DQ2). +- **Pass.** `./run.sh DP4`: `cmp` succeeds for every stream. + +### DP5 Write new data + +- **Goal.** Data Ray writes from nothing inflates correctly in zlib. +- **What happens.** `Deflate.write(input)` for each input, three ways: stored blocks only (`blocked`), with fixed codes, + and with dynamic codes (`Optimizations`). Each is written to `out/written/` and inflated by python3's `zlib`. +- **Why it matters.** Here the defaults compute the fields: `LEN` and `NLEN`, `HLIT`, `HDIST`, `HCLEN`, the code-length + code and its order. They have to agree with what follows them, which is where tools that build in both directions + usually give up. +- **Pass.** `./run.sh DP5`: zlib inflates every written stream to its input; Ray reads its own output to the input; DF7 + and DF8 print `ok`. Sizes are recorded, not compared. + +### DP6 Reject, and say where + +- **Goal.** A malformed stream answers no instance, and the runner reports the bit where reading stopped. +- **What happens.** `bad/` holds hand-built streams, each zlib also rejects, each with its expected stop offset: `BTYPE` + 3; `NLEN` not the complement of `LEN`; a copy reaching before the start of the output; over-subscribed code lengths; + incomplete code lengths (DQ5); a repeat code 16 with no length before it; a stream that ends before its final block; + literal/length symbol 286 under the fixed codes. +- **Why it matters.** A declaration that accepts what zlib rejects is wrong in a way DP3 cannot see. And a format tool + that only answers "no" hides its own bugs, the silent failure the strict runner exists for. +- **Pass.** `./run.sh DP6`: every bad stream answers `None`, python3's `zlib` raises on it, and the stop offset the runner + prints equals the one in `bad/manifest.txt` (DQ3). + +### DP7 Wrappers whose checksums cover everything + +- **Goal.** zlib and gzip files read, write back byte for byte, and are written new, with their checksums. +- **What happens.** `make.py` also wraps the small corpus as zlib (`wbits=15`) and gzip (`gzip -n`). The DP3, DP4 and DP5 + checks run again through `$.zlib` and `$.gzip`; written gzip files are checked with `gzip -t`. +- **Why it matters.** Adler-32 and CRC-32 depend on all of the data. In the declaration they are a default, + `adler: Binary₃₂ = adler32(inflated)`, so writing computes them, and reading checks them (`dynamically assert`). That + answers a field that depends on everything after it with a declaration, not with writer code. +- **Pass.** `./run.sh DP7`: reads match, rewrites `cmp` equal, `gzip -t` and python3's `zlib` accept every new file, and + DF9 prints `ok`. + +### DP8 Measure and compare + +- **Goal.** State the cost of one declaration, next to the tools it competes with. +- **What happens.** `README.md` gets a table for Ray, Kaitai Struct and Construct: the lines it takes to declare DEFLATE; + whether DEFLATE is declared or handed to zlib; whether reading and writing are one declaration or two; read speed on + `corpus/large/` next to python3's `zlib`. Each number carries the commit and date it was measured at. +- **Why it matters.** The claim is "one declaration, both ways, at this cost". The cost has to be known. +- **Pass.** Every cell is filled from a run, not from documentation, except where a tool cannot express the format, which + the cell says. No speed gate (DQ4). + +## After the proof: machine code + +### DP9 Read and write x86-64 encodings + +- **Goal.** The same mechanism reads gcc's output for `add` and writes it back. +- **What happens.** A declaration of the few x86-64 encodings involved (opcode, ModRM, SIB) reads gcc `-O2`'s bytes for + `int add(int a, int b) { return a + b; }`, `8d 04 37 c3` (`lea eax, [rdi+rsi*1]`, `ret`), and writes them back. +- **Why it matters.** This is the reading step of Interop.md C1 and the first piece of the Almanac's (1b): decompiling + the backends compilers already target. Machine code is one more binary format. +- **Not in this proof.** Built only after DP7 passes. + +## Status + +On 2026-10-11, on language3, through `Deflate.ray`: + +- **DP0** 17 claims, **DP2** DF1 to DF6: pass. +- **DP1**: 22 streams from 7 pinned inputs (zlib 1.3.2), stored, fixed and dynamic blocks. +- **DP3**: every one of the 22 read to what zlib inflates it to (0.03 s to 91 s a stream). +- **DP4**: every one written back byte for byte from the value read, by the same declaration. +- **DP5**: DF7 and DF8 pass (`"ray " * 64`, 256 bytes, is written in 8); each input written so zlib, and Ray, read it back. + The writer writes stored blocks, one fixed-code block, or one block with codes fitted to the data (`fitted`, its code + lengths run-length coded as zlib does), whichever is shortest: `text.txt`, 1240 bytes, is written in 334. +- **DP6**: the 7 streams in `bad/` zlib rejects answer no bytes; for the 4 that stop in their bits, at the bit expected. + Of the 3 that read and do not hold, only `far` depends on its check (a control without the checks reads it); `repeat` + and `oversubscribed` fail further on even without theirs, so they do not yet prove them. + +`./run.sh DP0` to `./run.sh DP6` in `@ether/poc/deflate` (each corpus stream in a process of its own). DP7 and DP8 are +next. + +Against the branch's base (`373672c9`), the language's own tests in `ray/tests/app` (control, types, grammar, +precedence, boolean, rewrite, string, ray, number) pass more claims with these changes, and lose none (measured with +`STEPS=300000`; the newer upstream main differs on its own). + +## Engine work + +What was fixed in language3 to get here, each found by a probe: + +- **`if a > b { … }`.** The `elsif` chain rule took `>` as a block. A body is no longer code that begins with an operator + and a space, a hole does not end in a dangling operator (`1 >`), the chain rules need the word `elsif` and are defined + after `else`. +- **Arguments of a method read on a number or text** (`3.binary(width)` in a call) were read at the outermost node, so a + call's own names were not seen; and after a chain passed through text (`a.binary.count < b.binary.count`), the node + before the text was taken for where the code was written. They are read where they were written. +- **`Name` in a header.** A hole no longer ends inside what follows a `<` written right after a word. +- **A host rule's body hole** (`plain { … }`) was run as code before the host saw it. It is given as text only. +- **Numerals** read through plain nodes (`Numeral`, `Numerals`), not classes, so the library's own `Digit` does not take + them; `0x…` is a host number, `0b…` host bits. Lists compare by value (`alike`), repeat (`xs * n`), and have `sort_by`, + `flatten`, `slice`, `join`, `index_of`. +- **Headers the library writes** read as classes: `class (h) { … }` without `=>`, `class byte: Byte`, a header over + several lines, `class (…)`. + +How a header of bits is read and written: + +- **The host moves bits; the declaration says what they are** (`v0.ts/src/structures3.ts`). A class whose header has a + piece that is not a parameter (an unnamed piece, a condition, a type of bits) is made by the host: its maker takes the + named pieces, a default is a rule read when its field is first read, and the header is kept as `structure`. + `T.bits_read(bits)` reads one, `x.binary` writes one. Every type, narrowing, condition and default is read in Ray with + the fields read so far; nothing in the host knows DEFLATE. +- **Widths.** `Binaryâ‚…` reads 5 bits, most significant first; `<-Binaryâ‚…` least significant first; `Byte` is `Binary₈`. A + narrowing `{length == n}` gives a `Binary` its width; any other narrowing of `length` or `at` is tried at each width. +- **Lists** read lazily: as few elements as let the rest of the header, and the list's narrowing, read. +- **Alternatives** read as a record holding every alternative's named pieces, each not read `None`; written, the first + alternative whose named pieces the record holds. +- **A prefix code** is `Coded(table)`: read by the bits that come next, written by the symbol. +- **Bits are text of `0` and `1`** (`0b010` is `"010"`). + +What `Deflate.ray` changed to run, each for a gap below: names of the enclosing class written in full +(`Deflate.LengthBases`), `Copy`'s header in brackets, `Symbol => Coded(codes)` (the original reads but cannot write), +helpers in loops and bracketed closures instead of sections and `reduce`, `65535` for `2 ^ 16 - 1`, `.first`/`.last` for +`.0`/`.1`, `&&` for chained comparisons, brackets around arithmetic compared and the code lengths' narrowing written +`(hlit + 257 + hdist + 1) == values.count`, `Stream.from(bytes)` and `written` for the `as` conversions, the stream's +narrowing `{!.empty && .last.final}`, `inflated`/`deflated` for `read`/`write`, `coded` making an `Element` (a class) for a +record of five fields, locals named apart from the library's (`stored_stream`), and `deflated` choosing between stored blocks and one fixed-code block in place of the +`Optimizations` level. `parsed` finds each match with the host's text search (`last_index_of`), the matching loop in Ray. +`fitted` counts with the host's `tally`; a copy before the first byte, a repeat with nothing before it, and a code length +code that does not fill its code answer None (`bytes`, `CodeLengths.values`). + +## Engine gaps + +A step blocked by the engine adds an entry here: the step, the probe file, its output, and what the engine would need. + +- **DPG1 A class does not see the names of the class it is written in.** `Outer.Inner(1).m` with `m => k` answers `"k"`: + an interior's outer is its parent class, not where it was written. `Deflate.ray` writes `Deflate.` before them. +- **DPG2 `x as T` is the library's.** With the library read, `"1001" as Pair` answers what one of the `as (=== T)` + methods the library gives `Node` makes of it, not the entrypoint's `as` (`T.from`, then the header): type-directed `as` + does not run. The reader is called as `T.bits_read(bits)`. +- **DPG3 Operators read on a value take the rest of the statement.** `3 % 8 == 0` is `3 % (8 == 0)`; arithmetic compared + needs brackets. +- **DPG4 `,` is the loosest rule**, so a header without brackets of more than one field (`class a: T, b: U`) is read as a + list. +- **DPG5 A name not given reads as its own text, which is true.** `None.final` is `"final"`, so a narrowing on a member + of `None` holds; written `!.empty && …` instead. +- **DPG6 `Language.read`/`write` do not run** (`Compiler.reduced`, levels, a typed hole converting a value), and `X.read` is + also the access keyword (`{who: Character}.read`, `Access.ray`). The proof calls `Deflate.inflated`/`deflated`. +- **DPG7 Sections and `reduce` with `.`.** `.map(. + 1)` passes a value, not a function; in `x -- f()`, `.` is not `x`. +- **DPG8 `^` is highlighting** (`2 ^ 16` is `2`), and `x.0` does not read. +- **DPG9 A method of a host number is reached through the numeral rule** (`{number: Number}` reads `half` as a member of + `Number`), so a typed hole reads a type's method names: the library's `{uuid: UUID.String}` reads `bytes`. The runner + places the host's rules after the library's when it reads them again. +- **DPG10 A record literal of four or more fields** gives its first field a list: `(a: 1, b: 2, c: 3, d: 4).a`. +- **DPG11 A host rule shadows a method of the same name for every value**: a host `slice({from}, {to})` for text read + `bytes.slice(…)` on a list whole and answered nothing; the host's text operation is `substring`. +- **DPG12 A narrowing `{length_code.fills && ((hlit + …) == values.count)}` did not hold for a valid block**, and broke + every dynamic block; the check is in `CodeLengths.values` instead. + +## Decided + +Answers from 2026-10-10: + +- This proof is the first step toward the interop vision, not a replacement for it: DP9 leads into Interop.md C1. +- DQ1 to DQ6 as recommended: a small corpus tier for DP3 to DP7 and a large one only in DP8; the padding pieces named, + so DP4 holds for every valid stream; the bit where reading stopped reported (an engine gap until it can be); speed + measured, not gated; incomplete Huffman codes rejected as zlib does; branched from main, interop kernel changes taken + only when a probe needs them. +- The engine is language3, fixed until `Deflate.ray` runs on it, not a new interpreter beside it, even though that takes + longer than a day. Kernel changes are commits of their own. + +## Order of work + +DP0, DP1, DP2, DP3, DP4, DP5, DP6, DP7, DP8. DP9 waits for DP7. diff --git a/@ether/v0.ts/src/js3.kinds.ray b/@ether/v0.ts/src/js3.kinds.ray index 483506298..236725aef 100644 --- a/@ether/v0.ts/src/js3.kinds.ray +++ b/@ether/v0.ts/src/js3.kinds.ray @@ -2,10 +2,11 @@ // the host's (`goto js`: the next statement is JS, `self` the value read on, each hole its value, `$(text)` text read here). // A port of `js.kinds.ray` to test with until the library reads numbers and text itself; read after the language. -// Numbers, as written: a digit (`Digit`'s own rules), digits, digits with a fraction (`Number`'s own rules: a typed hole -// `{n: Number}` takes what they read; what it took is read in `Number`). Read anywhere through the rule after them. -Digit := class { } -Digit &+= { +// Numbers, as written: a numeral (`Numeral`'s own rules), numerals after one another (`Numerals`'s), those with a fraction +// (`Number`'s own rules: a typed hole `{n: Number}` takes what they read; what it took is read in `Number`). Read anywhere +// through the rule after them. (Plain nodes, not classes, for the digits: the library defines a class `Digit` of its own.) +Numeral := { } +Numeral &+= { 0 => goto js 0 @@ -37,32 +38,92 @@ Digit &+= { goto js 9 } -// (digits after one another: what a number is written as, its own (the library adds to `Number`, not to it)) -Digits := class { } -Digits &+= { - {digit: Digit} => +Numerals := { } +Numerals &+= { + {digit: Numeral} => digit - {digit: Digit}{rest: Digits} => + {digit: Numeral}{rest: Numerals} => goto js Number($.text('digit') + $.text('rest')) } Number &+= { - {digits: Digits} => + {digits: Numerals} => digits - {whole: Digits}.{fraction: Digits} => + {whole: Numerals}.{fraction: Numerals} => goto js Number($.text('whole') + '.' + $.text('fraction')) } {number: Number} => number +// (a number written in hexadecimal, `0xff`: its hexadecimal digits, `Hexadecimals`'s own rules; a letter a name it holds, as +// a typed hole does not read a type's methods) +Hexadecimal_digit := { } +Hexadecimal_digit &+= { + 0 => + goto js + '0' + 1 => + goto js + '1' + 2 => + goto js + '2' + 3 => + goto js + '3' + 4 => + goto js + '4' + 5 => + goto js + '5' + 6 => + goto js + '6' + 7 => + goto js + '7' + 8 => + goto js + '8' + 9 => + goto js + '9' + a := "a" + b := "b" + c := "c" + d := "d" + e := "e" + f := "f" + A := "A" + B := "B" + C := "C" + D := "D" + E := "E" + F := "F" +} +Hexadecimals := { } +Hexadecimals &+= { + {digit: Hexadecimal_digit} => + digit + {digit: Hexadecimal_digit}{rest: Hexadecimals} => + digit +} +0x{digits: Hexadecimals} => + goto js + parseInt($.text('digits'), 16) +// Bits, as written: `0b010`, the text of its digits (it keeps its length; `+` joins two). +0b{digits: Numerals} => + goto js + /^[01]+$/.test($.text('digits')) ? $.text('digits') : undefined -// What both answer: `true`/`false`, read here. +// What both answer: `true`/`false`, read here. (Two lists: the same when their values are, `alike`.) == {other} => goto js - $(self === other ? 'true' : 'false') + self === other ? $('true') : typeof self === 'object' && self !== null && typeof other === 'object' && other !== null && $($.written(self) + '.listing') === $('true') && $($.written(self) + '.alike(' + $.written(other) + ')') === $('true') ? $('true') : $('false') != {other} => goto js - $(self !== other ? 'true' : 'false') + self === other ? $('false') : typeof self === 'object' && self !== null && typeof other === 'object' && other !== null && $($.written(self) + '.listing') === $('true') && $($.written(self) + '.alike(' + $.written(other) + ')') === $('true') ? $('false') : $('true') < {other} => goto js $(self < other ? 'true' : 'false') @@ -76,7 +137,7 @@ Number &+= { goto js $(self >= other ? 'true' : 'false') -// Numbers (text added to: joined; anything else, composed). +// Numbers (text added to: joined; anything else, composed; text or a list `* n`, it n times). + {other} => goto js typeof self === 'string' ? self + String(other) : typeof self === 'number' ? self + other : undefined @@ -86,7 +147,7 @@ Number &+= { self - other * {other} => goto js - self * other + typeof self === 'number' ? self * other : typeof self === 'string' ? self.repeat(other) : typeof self === 'object' && self !== null && $($.written(self) + '.listing') === $('true') ? $($.written(self) + '.repeated(' + $.written(other) + ')') : undefined / {other} => goto js self / other @@ -107,7 +168,6 @@ split({separator}) => count => goto js typeof self === 'string' ? [...self].length : undefined - // What a number or text is made of: Number, String (a node's own `of` is read before this). of => goto js @@ -125,3 +185,64 @@ of => . ..<({last}) ..{ }{last} => . ..({last}) + +// (bytes as text, one character each; a character's code; text from one place up to another; where text is last found, +// starting at or before a place, or -1) +latin1 => + goto js + typeof self === 'object' && self !== null && $($.written(self) + '.listing') === $('true') ? (function (codes) { for (let at = $($.written(self) + '.head'); at !== $('None'); at = $($.written(at) + '.next')) codes.push($($.written(at) + '.value')); return String.fromCharCode(...codes); })([]) : undefined +// (a list of whole numbers: how many times each of 0 up to `size` is in it; its largest) +tally({size}) => + goto js + typeof self === 'object' && self !== null && $($.written(self) + '.listing') === $('true') ? (function (counts) { for (let at = $($.written(self) + '.head'); at !== $('None'); at = $($.written(at) + '.next')) { const value = $($.written(at) + '.value'); if (typeof value === 'number' && value >= 0 && value < size) counts[value]++; } return $('[' + counts.join(', ') + ']'); })(new Array(size).fill(0)) : undefined +maximum => + goto js + typeof self === 'object' && self !== null && $($.written(self) + '.listing') === $('true') ? (function (largest) { for (let at = $($.written(self) + '.head'); at !== $('None'); at = $($.written(at) + '.next')) { const value = $($.written(at) + '.value'); if (typeof value === 'number' && value > largest) largest = value; } return largest; })(0) : undefined +code_at({index}) => + goto js + typeof self === 'string' ? self.charCodeAt(index) : undefined +substring({from}, {to}) => + goto js + typeof self === 'string' ? self.slice(from, to) : undefined +last_index_of({piece}, {before}) => + goto js + typeof self === 'string' ? self.lastIndexOf(piece, before) : undefined +// (text as the bytes UTF-8 writes it in) +bytes => + goto js + typeof self === 'string' ? (function (made) { for (const byte of new TextEncoder().encode(self)) $($.written(made) + '.append(' + byte + ')'); return made; })($('Listing.new')) : undefined +// (a whole number as bits: that many, the most significant first) +binary({width}) => + goto js + typeof self === 'number' && Number.isInteger(self) && self >= 0 ? self.toString(2).padStart(width, '0').slice(-width) : undefined +// (bits the other way around; the whole number they write, the most significant first; text in pieces of a size) +reversed => + goto js + typeof self === 'string' ? [...self].reverse().join('') : undefined +unsigned => + goto js + typeof self === 'string' && /^[01]*$/.test(self) ? (self.length ? parseInt(self, 2) : 0) : undefined +pieces({size}) => + goto js + typeof self === 'string' ? (function (made) { for (let at = 0; at < self.length; at += size) $($.written(made) + '.append("' + self.slice(at, at + size) + '")'); return made; })($('Listing.new')) : undefined + +// A class header as a structure of bits (`structures3.ts`): its maker given its named pieces, and the header as read; a value +// read from bits by it (`bits as T`); a value written as bits (`x.binary`); a table of symbols and their bits, a prefix code. +plain {{header}} => + goto js + $($.host.plain($, $.text('header')) ? 'true' : 'false') +instance_defined {{fields}} {{block}} => + goto js + $.host.instance($.text('fields'), $.text('block'), $.written).forEach(statement => $(statement)) +bits_read({bits}) => + goto js + $.host.read($, self, bits) +binary => + goto js + typeof self === 'object' && self !== null ? $.host.write($, self) : undefined +Coded({codes}) => + goto js + $.host.coding(codes, $) +begins {other} => + goto js + $(String(self).startsWith(String(other)) ? 'true' : 'false') diff --git a/@ether/v0.ts/src/language3.ts b/@ether/v0.ts/src/language3.ts index b98fe4203..1d8280933 100644 --- a/@ether/v0.ts/src/language3.ts +++ b/@ether/v0.ts/src/language3.ts @@ -1,4 +1,5 @@ import { sources } from './bundled.ts'; +import { Structures } from './structures3.ts'; export const NAME = 'Ether' as const export const ALIASES = ['ray', 'orbitmines'] as const; @@ -423,6 +424,11 @@ export class Program { // (nor one ending in an operator inside a longer one: `..` does not read the start of `..<`) static operator(s: string, i: number): boolean { return i >= 0 && i < s.length && '<>=!~|&+-*/%^?:.'.includes(s[i]); } static word(s: string, i: number): boolean { return i >= 0 && i < s.length && /[\p{L}\p{N}_]/u.test(s[i]); } + // (a hole ending in an operator after a space, `1 >`, is code its right operand is missing from: it ends nowhere there) + static dangling(s: string, t: number, u: number): boolean { + let v = u; while (v > t && '<>=!|&+-/%^~'.includes(s[v - 1])) v--; + return v < u && v > t && Program.space(s.charCodeAt(v - 1)); + } static space(c: number) { return c === 32 || c === 10 || c === 9 || c === 13; } static closes(s: string, i: number, open: string, close: string): number { let depth = 1, j = i + open.length; @@ -550,6 +556,9 @@ export class Program { } const following = pieces[k + 1]; if (!following || (following.literal === undefined && following.hole !== '')) return; + // (nor does code begin with an operator and then a space: `if a > b { … }` has no body `> b { … }`) + let u = t; while (Program.operator(s, u)) u++; + if (u > t && Program.space(s.charCodeAt(u))) return; } if (hole === '') { let u = t; while (Program.space(s.charCodeAt(u))) u++; if (u > t) step(k + 1, u); return; } const next = pieces[k + 1], last = !next, ends: number[] = [], enclosed = this.enclosed(rule, k); @@ -580,14 +589,16 @@ export class Program { if (u > t && (!typed || this.structural(s.slice(t, u), typed))) { spans.push(t, u); step(k + 1, u); spans.length -= 2; } return; } - for (let u = t, depth = 0; u < n;) { + // (nor inside what a class is given, `Name`: a `<` right after a word opens it) + for (let u = t, depth = 0, given = 0; u < n;) { const x = s.charCodeAt(u); if (x === o && s.startsWith(open, u)) { depth++; u += open.length; } else if (x === c && s.startsWith(close, u)) { if (--depth < 0) break; u += close.length; } else if (opens.has(x)) { depth++; u++; } else if (closes.has(x)) { if (--depth < 0) break; u++; } // (what is quoted: as one) else if (quoted.has(x)) { const q = Program.quote_end(s, u, s[u]); u = q < 0 ? n : q + 1; } - else if (x === 10 && !depth && !last && !enclosed) break; else u++; - if (depth > 0 || Program.space(s.charCodeAt(u - 1)) || (last && whole && u < n)) continue; + else if (x === 10 && !depth && !last && !enclosed) break; + else { if (x === 60 && Program.word(s, u - 1)) given++; else if (x === 62 && given > 0) given--; u++; } + if (depth > 0 || given > 0 || Program.space(s.charCodeAt(u - 1)) || (last && whole && u < n) || Program.dangling(s, t, u)) continue; if (last || (next.literal !== undefined ? s.startsWith(next.literal, u) : next.hole !== '' || Program.space(s.charCodeAt(u)))) ends.push(u); } for (let e = 0; e < ends.length; e++) { @@ -784,11 +795,14 @@ export class Program { const { reading } = frame, names = reading ? reading.rule.holes : []; let compiled = this.compiled.get(next!); if (!compiled) this.compiled.set(next!, compiled = new Function('self', '$', ...names, `return (${next});`) as (...args: unknown[]) => unknown); - const $ = Object.assign((text: string) => this.read(text, frame), { text: (name: string) => this.source(reading!.caps[name]) }); - return compiled(frame.this ?? frame.node, $, ...names.map(name => this.held_value(this.shared(reading!, name)))); + const $ = Object.assign((text: string) => this.read(text, frame), { text: (name: string) => this.source(reading!.caps[name]), written: (value: unknown) => typeof value === 'number' ? String(value) : this.written(value), host: this.layouts }); + // (a body hole is code: given as nothing, its text is `$.text(name)`) + return compiled(frame.this ?? frame.node, $, ...names.map(name => reading!.rule.bodies.has(name) ? undefined : this.held_value(this.shared(reading!, name)))); }], ]); private compiled = new Map unknown>(); + // (what the host's kinds use beyond JS: a class header read and written as bits) + layouts = new Structures(); declaring = new Set(); // (the rules whose right sides are running: a definition is not read by one of them) private running: Program.Rule[] = []; @@ -973,10 +987,12 @@ export class Program { // (read on in a value, it is `name` read in the value; else in `.`) // (where the text was written: read on in a value, where it was before; else here (what `site` holds here then is only // where else to look)) - const self = frame.on ? frame.node : 'receiver' in frame ? frame.receiver : frame.this ?? frame.node, written = frame.on ? frame.site ?? frame.node : frame.node; - // (a value that is not a node (text) has no names of its own: its names are the outermost node's (Node's), `.` the value) - if (!(self instanceof Program.Node)) { let root = frame.node; while (root.outer) root = root.outer; return this.read(s.slice(1), { node: root, from: self, this: self, writer: frame.reading ?? frame.writer }); } - return this.read(s.slice(1), { node: self, site: self === written ? undefined : written, this: frame.this, from: self, on: true, writer: frame.reading ?? frame.writer }); + const self = frame.on ? frame.node : 'receiver' in frame ? frame.receiver : frame.this ?? frame.node, written = frame.site ?? frame.node; + // (a value that is not a node (text) has no names of its own: its names are the outermost node's (Node's), `.` the value; + // what its holes take is read where it was written, `3.binary(width)` in a call) + if (!(self instanceof Program.Node)) { let root = frame.node; while (root.outer) root = root.outer; return this.read(s.slice(1), { node: root, site: written === root ? undefined : written, also: frame.also, from: self, this: self, writer: frame.reading ?? frame.writer }); } + // (and on through a chain, `x.count + y` in code read in a value: where else to look) + return this.read(s.slice(1), { node: self, site: self === written ? undefined : written, also: frame.also, this: frame.this, from: self, on: true, writer: frame.reading ?? frame.writer }); } if (s.startsWith('goto ')) return this.run(s, frame, except); // (a definition, its first line ending with the definer, is read only by a rule whose head has the definer) @@ -1159,7 +1175,7 @@ export class Program { const writer = frame.reading ?? frame.writer; // (`.` in a closure called in it: that value, as `x.f()` gives it; reading on a closure calls it: `.` as it was; a member // read on one, `.` that closure) - return node instanceof Program.Node ? this.evaluate(after, { node, site: frame.site ?? frame.node, from: node.calls && after.charCodeAt(0) !== 46 ? frame.from : node, this: frame.this, on: true, writer }, undefined, false) + return node instanceof Program.Node ? this.evaluate(after, { node, site: frame.site ?? frame.node, also: frame.also, from: node.calls && after.charCodeAt(0) !== 46 ? frame.from : node, this: frame.this, on: true, writer }, undefined, false) : this.evaluate(after, { node: frame.node, site: frame.site, also: frame.also, from: node, this: frame.this, receiver: node, writer }, except, false); } // A body: a value written into text (what it refers to), else a node its statements are read in (a new one each time; any diff --git a/@ether/v0.ts/src/structures3.ts b/@ether/v0.ts/src/structures3.ts new file mode 100644 index 000000000..40508d0f2 --- /dev/null +++ b/@ether/v0.ts/src/structures3.ts @@ -0,0 +1,378 @@ +// A class header read as a structure of bits: its pieces walked over a sequence of bits to read a value, or over a value to +// write its bits. What each piece is (its type, narrowing, condition, default) is the header's, read in Ray with the fields +// read so far; this only moves bits. Bits are text of `0` and `1`. + +type Ray = ((text: string) => unknown) & { written: (value: unknown) => string }; +// (a value as code: text quoted, as the kernel writes text as itself) +const code = ($: Ray, value: unknown) => typeof value === 'string' ? (value.includes('"') ? '`' + value + '`' : '"' + value + '"') : $.written(value); +type Type = { + text: string, reversed?: boolean, width?: number, variable?: boolean, base?: string, generics?: string[], + list?: Type, group?: Piece[], alternatives?: Type[], narrowings: string[], boolean?: boolean, +}; +type Piece = { name?: string, type?: Type, default?: string, condition?: string, group?: Piece[] }; +type Header = { pieces: Piece[], parameters: string, plain: boolean }; +type Read = { value: unknown, at: number }; +type Then = (value: unknown, at: number) => Read | null; + +const SUBSCRIPTS = 'â‚€â‚�₂₃₄₅₆₇₈₉'; + +export class Structures { + // (the furthest bit the last read reached: where reading a value that is not one stopped) + reached = 0; + private headers = new Map(); + private codings = new WeakMap(); + + // (the pieces of a header, split where a comma is outside every bracket) + static split(text: string, separator: string): string[] { + const parts: string[] = [], open: string[] = []; + let start = 0, quote = ''; + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (quote) { if (c === '\\') i++; else if (c === quote) quote = ''; continue; } + if (c === '"' || c === '`') quote = c; + else if ('([{'.includes(c) || (c === '<' && /[\p{L}\p{N}_]/u.test(text[i - 1] ?? '') && text[i + 1] !== '-' && text[i + 1] !== '=')) open.push(c); + else if (')]}'.includes(c) || (c === '>' && open.at(-1) === '<')) open.pop(); + else if (!open.length && text.startsWith(separator, i)) { parts.push(text.slice(start, i).trim()); start = i + separator.length; i += separator.length - 1; } + } + parts.push(text.slice(start).trim()); + return parts.filter(part => part.length); + } + static closing(text: string, at: number): number { + const open = text[at], close = open === '(' ? ')' : open === '[' ? ']' : '}'; + let depth = 0; + for (let i = at; i < text.length; i++) { if (text[i] === open) depth++; else if (text[i] === close && --depth === 0) return i; } + return -1; + } + static opening(text: string, end: number): number { + const close = text[end], open = close === ')' ? '(' : close === ']' ? '[' : '{'; + let depth = 0; + for (let i = end; i >= 0; i--) { if (text[i] === close) depth++; else if (text[i] === open && --depth === 0) return i; } + return -1; + } + + // (a header of bits: one with a piece that is not named, a condition, or a type of bits in it; any other is plain, its + // pieces its maker's parameters as written) + header(text: string): Header { + let header = this.headers.get(text); + if (header) return header; + const written = text.split('\n').filter(line => !line.trim().startsWith('//')).join('\n').trim(); + const pieces = Structures.split(written, ',').map(piece => this.piece(piece)); + const plain = pieces.every(piece => piece.name !== undefined && !piece.group && !/\b(Binary|Byte)|<-/.test(piece.type?.text ?? '')); + header = { pieces, plain, parameters: plain ? written : Structures.named(pieces).map(piece => piece.name).join(', ') }; + this.headers.set(text, header); + return header; + } + // (plain, and no piece's type a class whose header is of bits) + plain($: Ray, text: string): boolean { + const header = this.header(text); + if (!header.plain) return false; + for (const piece of header.pieces) { + const base = piece.type?.base; + if (!base || !/^[\p{Lu}][\p{L}\p{N}_]*$/u.test(base)) continue; + const structure = $(base + '.structure'); + if (structure && typeof structure === 'object' && 'pieces' in structure) return false; + } + return true; + } + static names(type: Type): string[] { return type.group ? Structures.named(type.group).map(piece => piece.name!) : []; } + static named(pieces: Piece[]): Piece[] { return pieces.flatMap(piece => piece.group ? Structures.named(piece.group) : piece.name === undefined ? [] : [piece]); } + // (the maker's definition: in a header of bits, a default is a rule read when its field is first read, unless given) + instance(fields: string, block: string, written: (value: unknown) => string): string[] { + const header = this.header(fields), lines = block.split('\n'), base = Math.min(...lines.filter(line => line.trim()).map(line => line.length - line.trimStart().length)); + const defaults = Structures.named(header.pieces).filter(piece => piece.default !== undefined) + .map(piece => `\n (goto given_${piece.name}) unless ${piece.name} === None\n ${piece.name} =>\n ${piece.default}\n given_${piece.name}\\`).join(''); + const maker = `instance := (${Structures.named(header.pieces).map(piece => piece.name).join(', ')}) =>\n of := instance\n (here of) instanced {\n${lines.map(line => ' ' + line.slice(base)).join('\n')}\n }${defaults}\n of := instance`; + return [maker, `structure := ${written(header)}`]; + } + piece(text: string): Piece & { written?: string } { + if (text.startsWith('(')) { + const close = Structures.closing(text, 0), guard = close > 0 ? /^\s+if\s+([\s\S]+)$/.exec(text.slice(close + 1)) : null; + if (guard) return { group: Structures.split(text.slice(1, close), ',').map(piece => this.piece(piece)), condition: guard[1].trim() }; + } + const name = /^([\p{L}_][\p{L}\p{N}_]*)(\s*:\s+|\s*=\s+|$)/u.exec(text); + if (!name || (name[2].trim() === '' && name[0] !== text)) return { type: this.type(text) }; + const rest = text.slice(name[0].length), assigned = name[2].trim() === '='; + if (assigned) return { name: name[1], default: rest.trim(), written: text }; + const parts = Structures.split(rest, ' = '); + return { name: name[1], type: rest ? this.type(parts[0]) : undefined, default: parts.length > 1 ? parts.slice(1).join(' = ') : undefined, written: parts.length > 1 ? `${name[1]}: ${parts[0]} = ${parts.slice(1).join(' = ')}` : text }; + } + type(written: string): Type { + let text = written.trim(); + const type: Type = { text, narrowings: [] }; + const alternatives = Structures.split(text, ' | '); + if (alternatives.length > 1) return { ...type, alternatives: alternatives.map(alternative => this.type(alternative)) }; + const as = /\s+as\s+boolean$/.exec(text); + if (as) { type.boolean = true; text = text.slice(0, as.index).trim(); } + for (;;) { + if (text.endsWith('}')) { const at = Structures.opening(text, text.length - 1); if (at > 0) { type.narrowings.unshift(text.slice(at + 1, -1).trim()); text = text.slice(0, at).trim(); continue; } } + break; + } + if (text.endsWith('[]')) { type.list = this.type(text.slice(0, -2)); return type; } + if (text.startsWith('(') && Structures.closing(text, 0) === text.length - 1) { + const inner = text.slice(1, -1).trim(), parts = Structures.split(inner, ','); + if (parts.length > 1 || /^[\p{L}_][\p{L}\p{N}_]*\s*:\s/u.test(inner)) { type.group = parts.map(part => this.piece(part)); return type; } + const inside = this.type(inner); + return { ...inside, narrowings: [...inside.narrowings, ...type.narrowings], boolean: inside.boolean || type.boolean }; + } + if (text.startsWith('<-')) { type.reversed = true; text = text.slice(2).trim(); if (text.startsWith('(')) { const inside = this.type(text); return { ...inside, reversed: true, narrowings: [...inside.narrowings, ...type.narrowings] }; } } + const fixed = /^(Binary|Byte)([â‚€-₉]*)$/.exec(text); + if (fixed) { + const count = fixed[2] ? Number([...fixed[2]].map(digit => SUBSCRIPTS.indexOf(digit)).join('')) : undefined; + if (fixed[1] === 'Byte') type.width = 8 * (count ?? 1); else if (count === undefined) type.variable = true; else type.width = count; + return type; + } + const generic = /^([\s\S]+?)<([\s\S]+)>$/.exec(text); + if (generic && !generic[1].includes(' ')) { type.base = generic[1]; type.generics = Structures.split(generic[2], ','); return type; } + type.base = text; + return type; + } + + coding(table: object, $: Ray): Coding { + let coding = this.codings.get(table); + if (!coding) this.codings.set(table, coding = new Coding(listed($, table).map(entry => ({ symbol: $($.written(entry) + '.symbol') as number, bits: $($.written(entry) + '.bits') as string })))); + return coding; + } + + read($: Ray, maker: unknown, bits: string): unknown { + if (typeof bits !== 'string' || !/^[01]*$/.test(bits) || typeof maker !== 'object' || maker === null) return $('None'); + const header = $($.written(maker) + '.structure'); + if (!header || typeof header !== 'object' || !('pieces' in header)) return $('None'); + const reading = new Reading(this, $, bits); + const read = reading.structure(maker, [], 0, header as Header, (value, at) => ({ value, at })); + this.reached = reading.furthest; + return read ? read.value : $('None'); + } + write($: Ray, value: unknown): string | undefined { + const writing = new Writing(this, $); + return writing.structure(value, 0) ? writing.out.join('') : undefined; + } +} + +// A prefix code: a table of symbols and their bits, read by the bits that come next, written by the symbol. +export class Coding { + private by_bits = new Map(); private by_symbol = new Map(); longest = 0; + constructor(entries: { symbol: number, bits: string }[]) { + for (const { symbol, bits } of entries) { this.by_bits.set(bits, symbol); this.by_symbol.set(symbol, bits); this.longest = Math.max(this.longest, bits.length); } + } + read(bits: string, at: number): Read | null { + for (let width = 1; width <= this.longest && at + width <= bits.length; width++) { + const symbol = this.by_bits.get(bits.slice(at, at + width)); + if (symbol !== undefined) return { value: symbol, at: at + width }; + } + return null; + } + bits(symbol: number): string | undefined { return this.by_symbol.get(symbol); } +} + +function listed($: Ray, list: unknown): unknown[] { + const values: unknown[] = [], none = $('None'); + for (let at = $($.written(list) + '.head'); at !== none && at !== undefined; at = $($.written(at) + '.next')) values.push($($.written(at) + '.value')); + return values; +} +function truthy($: Ray, value: unknown): boolean { return value !== undefined && value !== $('None') && value !== $('false'); } +function unsigned(bits: string, reversed?: boolean): number { + const read = reversed ? [...bits].reverse().join('') : bits; + return read.length ? parseInt(read, 2) : 0; +} +function bits_of(value: number, width: number, reversed?: boolean): string { + const written = width ? value.toString(2).padStart(width, '0').slice(-width) : ''; + return reversed ? [...written].reverse().join('') : written; +} + +// What both directions share: reading Ray in a scope (an instance, a record being made), with `.`, `length` and `at` given. +class Scoped { + // (a record's scope, made in a structure's: what is read in it that names none of its fields is the same for the structure) + private homes = new WeakMap }>(); private made_in = new WeakMap>(); + constructor(protected structures: Structures, protected $: Ray) {} + in(scope: unknown, text: string): unknown { return this.$(this.$.written(scope) + ' reading {\n' + text + '\n}'); } + set(scope: unknown, name: string, value: unknown) { this.in(scope, `${name} = ${code(this.$, value)}`); } + child(scope: unknown): unknown { return this.in(scope, '{ }'); } + given(scope: unknown, length: number, at: number): unknown { + const child = this.child(scope); + this.in(child, `length := ${length}\nat := ${at}`); + return child; + } + // (a narrowing read with `.` the value; one beginning with an operator, `{< 256}`, of `.`; one of where the value is, + // `length` (its bits, or values) and `at` (the bit it begins at), read where those are) + holds(scope: unknown, narrowing: string, value: unknown, length: number, at: number): boolean { + const exact = /^==\s*([\s\S]+)$/.exec(narrowing); + if (exact && typeof value === 'number') return this.in(scope, exact[1]) === value; + const held = /\b(length|at)\b/.test(narrowing) ? this.in(this.given(scope, length, at), narrowing) + : this.in(scope, `(${this.$.written(value)}) with {\n${/^[<>=!]/.test(narrowing) ? '. ' + narrowing : narrowing}\n}`); + return truthy(this.$, held); + } + // (a narrowing that fixes `length`, `length == n`: n; else none) + fixed_length(scope: unknown, narrowings: string[]): number | undefined { + for (const narrowing of narrowings) { const fixed = /^length\s*==\s*([\s\S]+)$/.exec(narrowing); if (fixed) return this.in(scope, fixed[1]) as number; } + return undefined; + } + // (a narrowing that fixes the value, `== v`: v; else none) + exact(scope: unknown, narrowings: string[]): unknown { + for (const narrowing of narrowings) { const exact = /^==\s*([\s\S]+)$/.exec(narrowing); if (exact) return this.in(scope, exact[1]); } + return undefined; + } + record_scope(scope: unknown, names: string[]): unknown { + const record = this.child(scope), outer = this.homes.get(scope as object); + this.homes.set(record as object, { home: outer ? outer.home : scope, names: new Set([...names, ...(outer?.names ?? [])]) }); + return record; + } + made(scope: unknown, base: string): { maker: unknown, header?: Header, coding?: Coding } { + const record = this.homes.get(scope as object), words = base.match(/[\p{L}_][\p{L}\p{N}_]*/gu) ?? []; + const home = record && !words.some(word => record.names.has(word)) ? record.home : scope; + let known = this.made_in.get(home as object); + if (!known) this.made_in.set(home as object, known = new Map()); + const had = known.get(base); + if (had) return had; + const made = this.making(home, base); + known.set(base, made); + return made; + } + making(scope: unknown, base: string): { maker: unknown, header?: Header, coding?: Coding } { + const maker = this.in(scope, base); + if (maker instanceof Object && (maker as { coding?: unknown }).constructor === Coding) return { maker, coding: maker as Coding }; + const header = this.$(this.$.written(maker) + '.structure'); + return { maker, header: header && typeof header === 'object' && 'pieces' in (header as object) ? header as Header : undefined }; + } + // (a record of the named pieces read, the scope they were read in, each one not read None: of every alternative, so what one + // does not hold reads as None) + record(scope: unknown, names: string[], values: Map): unknown { + if (!names.length) return this.$('None'); + const missing = names.filter(name => !values.has(name)); + if (missing.length) this.in(scope, missing.map(name => `${name} := None`).join('\n')); + return scope; + } + +} + +class Reading extends Scoped { + furthest = 0; + constructor(structures: Structures, $: Ray, private bits: string) { super(structures, $); } + reach(at: number) { if (at > this.furthest) this.furthest = at; } + + structure(maker: unknown, given: unknown[], at: number, header: Header | undefined, then: Then): Read | null { + header ??= this.$(this.$.written(maker) + '.structure') as Header; + const made = this.$(this.$.written(maker) + '(' + given.map(value => code(this.$, value)).join(', ') + ')'); + return this.pieces(header.pieces.slice(given.length), 0, at, made, undefined, after => then(made, after)); + } + pieces(pieces: Piece[], k: number, at: number, scope: unknown, values: Map | undefined, then: (at: number) => Read | null): Read | null { + if (k === pieces.length) return then(at); + const piece = pieces[k]; + if (piece.group) { + if (piece.condition !== undefined && !truthy(this.$, this.in(scope, piece.condition))) return this.pieces(pieces, k + 1, at, scope, values, then); + return this.pieces([...piece.group, ...pieces.slice(k + 1)], 0, at, scope, values, then); + } + if (!piece.type) return this.pieces(pieces, k + 1, at, scope, values, then); + return this.type(piece.type, at, scope, (value, after) => { + if (piece.name) { if (values) { values.set(piece.name, value); this.in(scope, `${piece.name} := ${code(this.$, value)}`); } else this.set(scope, piece.name, value); } + return this.pieces(pieces, k + 1, after, scope, values, then); + }); + } + type(type: Type, at: number, scope: unknown, then: Then, names?: string[]): Read | null { + if (type.alternatives) { const all = type.alternatives.flatMap(alternative => Structures.names(alternative)); for (const alternative of type.alternatives) { const read = this.type(alternative, at, scope, then, all); if (read) return read; } return null; } + const narrowed: Then = type.narrowings.length || type.boolean ? (value, after) => { + for (const narrowing of type.narrowings) if (!this.holds(scope, narrowing, value, typeof value === 'number' || typeof value === 'string' ? after - at : this.$(this.$.written(value) + '.count') as number, at)) return null; + return then(type.boolean ? this.$(value ? 'true' : 'false') : value, after); + } : then; + if (type.width !== undefined && at + type.width <= this.bits.length) this.reach(at + type.width); + if (type.width !== undefined) return at + type.width <= this.bits.length ? narrowed(unsigned(this.bits.slice(at, at + type.width), type.reversed), at + type.width) : null; + if (type.variable) { + const fixed = this.fixed_length(scope, type.narrowings); + if (fixed !== undefined && at + fixed <= this.bits.length) this.reach(at + fixed); + if (fixed !== undefined) return at + fixed <= this.bits.length ? then(unsigned(this.bits.slice(at, at + fixed), type.reversed), at + fixed) : null; + for (let width = 0; width <= 64 && at + width <= this.bits.length; width++) { + const value = unsigned(this.bits.slice(at, at + width), type.reversed); + if (type.narrowings.every(narrowing => this.holds(scope, narrowing, value, width, at))) { const read = then(value, at + width); if (read) return read; } + } + return null; + } + if (type.list) return this.list(type, at, scope, then); + if (type.group) { + const record = this.record_scope(scope, Structures.names(type)), values = new Map(); + return this.pieces(type.group, 0, at, record, values, after => narrowed(this.record(record, names ?? Structures.names(type), values), after)); + } + const { maker, header, coding } = this.made(scope, type.base!); + if (coding) { const read = coding.read(this.bits, at); if (read) this.reach(read.at); return read ? narrowed(read.value, read.at) : null; } + if (!header) return null; + const given = (type.generics ?? []).map(generic => this.in(scope, generic)); + return this.structure(maker, given, at, header, narrowed); + } + list(type: Type, at: number, scope: unknown, then: Then): Read | null { + const made = this.$('Listing.new'), fixed = this.fixed_length(scope, type.narrowings); + const rest = type.narrowings.filter(narrowing => !/^length\s*==/.test(narrowing)); + for (let count = 0, after = at; ; count++) { + if (fixed === undefined || count === fixed) { + if (rest.every(narrowing => this.holds(scope, narrowing, made, count, at))) { const read = then(made, after); if (read) return read; } + if (fixed !== undefined) return null; + } + const element = this.type(type.list!, after, scope, (value, next) => ({ value, at: next })); + if (!element || element.at === after) return null; + this.$(this.$.written(made) + '.append(' + code(this.$, element.value) + ')'); + after = element.at; + } + } +} + +class Writing extends Scoped { + out: string[] = []; private length = 0; + emit(bits: string) { this.out.push(bits); this.length += bits.length; } + + structure(value: unknown, given: number, header?: Header): boolean { + header ??= this.$(this.$.written(value) + '.of.structure') as Header; + if (!header || typeof header !== 'object') return false; + return this.pieces(header.pieces.slice(given), value, value); + } + field(scope: unknown, record: unknown, piece: Piece): unknown { + let value = this.$(this.$.written(record) + '.' + piece.name); + if (!truthy(this.$, value) && value !== this.$('false') && piece.default !== undefined) { value = this.in(scope, piece.default); if (record === scope) this.set(scope, piece.name!, value); } + return value; + } + pieces(pieces: Piece[], scope: unknown, record: unknown): boolean { + for (const piece of pieces) { + if (piece.group) { + if (piece.condition !== undefined && !truthy(this.$, this.in(scope, piece.condition))) continue; + if (!this.pieces(piece.group, scope, record)) return false; + continue; + } + if (!piece.type) continue; + const value = piece.name ? this.field(scope, record, piece) : undefined; + if (!this.type(piece.type, value, scope)) return false; + } + return true; + } + type(type: Type, value: unknown, scope: unknown): boolean { + if (type.alternatives) { + for (const alternative of type.alternatives) if (this.fits(alternative, value)) return this.type(alternative, value, scope); + return false; + } + if (value === this.$('None')) value = undefined; + if (value === undefined) value = this.exact(scope, type.narrowings); + if (type.boolean) value = value === this.$('true') ? 1 : 0; + if (type.width !== undefined) { this.emit(bits_of((value ?? 0) as number, type.width, type.reversed)); return true; } + if (type.variable) { + let width = this.fixed_length(scope, type.narrowings); + for (let tried = 0; width === undefined && tried <= 64; tried++) if (type.narrowings.every(narrowing => this.holds(scope, narrowing, value ?? 0, tried, this.length))) width = tried; + if (width === undefined) return false; + this.emit(bits_of((value ?? 0) as number, width, type.reversed)); + return true; + } + if (type.list) { for (const element of listed(this.$, value)) if (!this.type(type.list, element, scope)) return false; return true; } + if (type.group) { + const record = this.child(scope); + const walk = (pieces: Piece[]) => { for (const piece of pieces) if (piece.name) this.in(record, `${piece.name} := ${code(this.$, this.$(this.$.written(value) + '.' + piece.name))}`); else if (piece.group) walk(piece.group); }; + walk(type.group); + return this.pieces(type.group, record, value); + } + const { header, coding } = this.made(scope, type.base!); + if (coding) { const bits = coding.bits(value as number); if (bits === undefined) return false; this.emit(bits); return true; } + if (!header) return false; + return this.structure(value, (type.generics ?? []).length, header); + } + // (the alternative a record was read as: the one whose named pieces it holds) + fits(type: Type, value: unknown): boolean { + if (!type.group) return true; + const names: string[] = []; + const walk = (pieces: Piece[]) => { for (const piece of pieces) if (piece.name) names.push(piece.name); else if (piece.group) walk(piece.group); }; + walk(type.group); + return names.every(name => truthy(this.$, this.$(this.$.written(value) + '.' + name)) || this.$(this.$.written(value) + '.' + name) === 0); + } +}