diff --git a/src/Rosetta/data/cbor/Codec.luau b/src/Rosetta/data/cbor/Codec.luau index f99bb05..26ff2ff 100644 --- a/src/Rosetta/data/cbor/Codec.luau +++ b/src/Rosetta/data/cbor/Codec.luau @@ -1,7 +1,6 @@ --!strict --!native --- data/cbor/Codec: the CBOR (RFC 8949) decoder and encoder behind data/cbor. Never throws: errors return nil, --- message, offset. +-- data/cbor/Codec: CBOR (RFC 8949) decoder and encoder; never throws (errors return nil, message, offset). local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -16,14 +15,13 @@ end } local SimpleMeta = { __tostring = function(s: any): string return "cbor.simple(" .. s.value .. ")" end } --- tagged(tag, value) -> { tag, value }: a tag this library does not interpret function Codec.tagged(tag: number, value: any): { tag: number, value: any } return setmetatable({ tag = tag, value = value }, TaggedMeta) :: any end function Codec.isTagged(v: any): boolean return type(v) == "table" and getmetatable(v) == TaggedMeta end --- simple(n) -> an unassigned simple value (0..19, 32..255) +-- unassigned simple values: 0..19, 32..255 function Codec.simple(n: number): { value: number } return setmetatable({ value = n }, SimpleMeta) :: any end @@ -34,7 +32,6 @@ Codec.undefined = table.freeze(setmetatable({}, { __tostring = function() return "undefined" end })) --- decimal text of a big-endian unsigned byte string (any length) local function bigText(s: string): string local limbs = {} -- base 1e7, little-endian for i = 1, #s do @@ -58,7 +55,6 @@ local function bigText(s: string): string end return table.concat(out) end --- text + 1 for a decimal string local function incText(s: string): string local digits: { number } = table.create(#s) :: { number } for i = 1, #s do @@ -81,18 +77,18 @@ local function incText(s: string): string end export type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers / bignums past 2^53: "string" keeps exact decimal text - null: any?, -- the value for null (default Types.null) - undefined: any?, -- the value for undefined (default Codec.undefined) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + undefined: any?, -- default Codec.undefined maxDepth: number?, -- default 512 - dates: boolean?, -- tags 0 / 1 as Types.Date (default true) + dates: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, undef: any, maxDepth: number, dates: boolean } -local BREAK = {} -- the 0xFF stop code, inside indefinite items +local BREAK = {} -- 0xFF break stop code --- the argument of a head: number (or nil, "text" for u64 past 2^53 when big), nil means indefinite (ai 31) +-- additional information 31: indefinite length local function arg(st: St, ai: number): (number?, string?, string?) local r = st.r if ai < 24 then @@ -169,7 +165,7 @@ local function tag(st: St, t: number, v: any): (any, string?) n = n * 256 + string.byte(s, i) end if n >= 9007199254740992 then - -- exact text; as a number, read back from that text (correctly rounded, unlike the running sum) + -- read back from the exact text: correctly rounded, unlike the running sum local text = bigText(s) if t == 3 then text = incText(text) @@ -347,7 +343,6 @@ function item(st: St, depth: number): (any, string?) if v == BREAK then return nil, "unexpected break" end - -- bignum content arrives as a buffer: hand the tag its bytes if (n == 2 or n == 3) and type(v) == "buffer" then return tag(st, n, buffer.tostring(v)) end @@ -355,7 +350,6 @@ function item(st: St, depth: number): (any, string?) end end --- decode(r, opts) -> value | nil, message, offset (one item; r is left after it) function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -378,10 +372,10 @@ end -- ------------------------------------------------------------------------------------------------ encode export type EncodeOptions = { - compactFloats: boolean?, -- floats in the shortest of half / single / double that keeps the value (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") - dates: ("string" | "epoch")?, -- Types.Date as tag 0 text (default) or tag 1 seconds + compactFloats: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" + dates: ("string" | "epoch")?, -- tag 0 text (default) or tag 1 epoch seconds maxDepth: number?, -- default 512 (also catches cycles) } @@ -410,7 +404,6 @@ local function head(w: Bytes.Writer, major: number, n: number) end end --- the half-float bits of x when x is exactly representable, else nil local function toHalf(x: number): number? if x ~= x then return 0x7E00 @@ -423,7 +416,7 @@ local function toHalf(x: number): number? if a == 0 then return sign end - local m, e = math.frexp(a) -- a = m * 2^e, 0.5 <= m < 1 + local m, e = math.frexp(a) local exp = e - 1 + 15 if exp >= 31 then return nil @@ -554,7 +547,6 @@ local function enc(st: ESt, v: any, depth: number): boolean return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { diff --git a/src/Rosetta/data/cbor/init.luau b/src/Rosetta/data/cbor/init.luau index 9867917..4865c60 100644 --- a/src/Rosetta/data/cbor/init.luau +++ b/src/Rosetta/data/cbor/init.luau @@ -1,10 +1,7 @@ --!strict --- data/cbor: CBOR (RFC 8949). New code. Supports: every major type, indefinite-length strings / arrays / maps, half / --- single / double floats, tags (0 / 1 date-times as Types.Date, 2 / 3 bignums as numbers or exact decimal text, --- 55799 self-describe stripped, others kept as Cbor.tagged(tag, value)), simple values (Cbor.simple(n), --- Cbor.undefined), byte strings as buffers, maps as Types.object (key order kept; keys of any type), sequences --- (RFC 8742, opts.all). Encode: preferred (shortest) integer and length heads, float64 unless opts.compactFloats, --- definite lengths. Not supported: other semantic tags (decimal fractions, bigfloats, ...) stay tagged values. +-- data/cbor: CBOR (RFC 8949), new code. Supports: every major type, indefinite lengths, half / single / double +-- floats, tags 0 / 1 (Types.Date), 2 / 3 (bignums), 55799 (stripped), others as Cbor.tagged; simple values; sequences +-- (RFC 8742). Encode: shortest heads, definite lengths. Not supported: other semantic tags (kept as tagged values). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -22,11 +19,11 @@ local Cbor = { } export type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- a CBOR sequence: every item into an array (default false: exactly one item) + all: boolean?, -- default false } export type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of items, written as a sequence - selfDescribe: boolean?, -- prefix the 55799 self-describe tag (d9 d9 f7) + all: boolean?, + selfDescribe: boolean?, -- 55799 tag prefix (d9 d9 f7) } -- ------------------------------------------------------------------------------------------------ sniff @@ -91,9 +88,9 @@ function Cbor.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Cbor.tagged = Codec.tagged -- tagged(tag, value) -> a value written as that tag +Cbor.tagged = Codec.tagged Cbor.isTagged = Codec.isTagged -Cbor.simple = Codec.simple -- simple(n) -> a simple value +Cbor.simple = Codec.simple Cbor.isSimple = Codec.isSimple Cbor.undefined = Codec.undefined diff --git a/src/Rosetta/data/csv/init.luau b/src/Rosetta/data/csv/init.luau index b4638f8..8f733b4 100644 --- a/src/Rosetta/data/csv/init.luau +++ b/src/Rosetta/data/csv/init.luau @@ -1,10 +1,7 @@ --!strict --- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv module). New code. Supports: any --- one-byte delimiter (opts.delimiter, or "auto" to pick , ; tab |), quoted fields with doubled quotes and embedded --- line breaks, CRLF / LF / CR line ends, a header row (opts.header: rows become Types.object keyed by the column --- names, in column order), number conversion by option; encode from arrays of arrays or of keyed rows, quoting only --- where needed (like Python's QUOTE_MINIMAL) or always. Blank lines are skipped. Not supported: escape characters --- other than the doubled quote, multi-byte delimiters. +-- data/csv: comma-separated values (RFC 4180, read as leniently as Python's csv), new code. Supports: one-byte or +-- "auto" delimiter, quoted fields with "" and line breaks, CRLF / LF / CR, header rows, numbers by option; encode +-- quotes minimally (QUOTE_MINIMAL) or always. Not supported: other escapes, multi-byte delimiters. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,19 +21,19 @@ local Csv = { } export type DecodeOptions = { - delimiter: string?, -- one byte (default ","; "auto" guesses from the first line among , ; tab |) - quote: string?, -- the quote byte (default '"') - header: boolean?, -- the first row names the columns: rows become Types.object (default false: arrays) - numbers: boolean?, -- fields that are numbers become numbers (default false: every field is a string) - maxRows: number?, -- refuse more rows (default unlimited) + delimiter: string?, -- default ","; "auto": one of , ; tab | + quote: string?, -- default '"' + header: boolean?, -- default false + numbers: boolean?, -- default false + maxRows: number?, -- default unlimited } export type EncodeOptions = { delimiter: string?, -- default "," quote: string?, -- default '"' - newline: string?, -- the row terminator (default "\r\n", as RFC 4180 and Python's csv) - quoteAll: boolean?, -- quote every field (default false: only those that need it) - columns: { string }?, -- keyed rows: the column order (default: the keys of the rows in first-seen order) - header: boolean?, -- keyed rows: write the header row (default true) + newline: string?, -- default "\r\n" (RFC 4180) + quoteAll: boolean?, -- default false + columns: { string }?, -- default: keys in first-seen order + header: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ constants @@ -80,7 +77,6 @@ local function guess(s: string, q: string): string return best end --- rows(s, opts) -> { { string } } | nil, Err function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local o: DecodeOptions = opts or {} local q = o.quote or '"' @@ -98,7 +94,7 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) local row: { string } = {} local n = #s local i = 1 - local rowEmpty = true -- the current line has no field text yet (blank lines are skipped) + local rowEmpty = true while true do local c = byte(s, i) local field: string @@ -141,7 +137,6 @@ function Csv.parse(s: string, opts: DecodeOptions?): ({ { string } }?, Err.Err?) rowEmpty = false i += 1 else - -- end of the row: CRLF / LF / CR / end of data if c == 13 and byte(s, i + 1) == 10 then i += 2 elseif c ~= nil then diff --git a/src/Rosetta/data/ini/init.luau b/src/Rosetta/data/ini/init.luau index 48f9f70..9a9914d 100644 --- a/src/Rosetta/data/ini/init.luau +++ b/src/Rosetta/data/ini/init.luau @@ -1,11 +1,7 @@ --!strict --- data/ini: INI / config files, read the way Python's configparser does (interpolation off, key case kept). New code. --- Supports: [sections] (name = everything between the first '[' and the last ']'), key = value and key: value, --- ; and # comment lines (indented too), indented continuation lines (joined with "\n"), keys before any section (at --- the top level), duplicate keys / sections (the last value wins, sections merge), inline comments, keys without a --- value and typed values by option. Decodes to a Types.object of sections (each a Types.object of strings), top-level --- keys beside them. Encode writes configparser's layout ("key = value", a blank line after each section, nested --- tables as dotted section names). Not supported: interpolation, the DEFAULT section's inheritance, escapes. +-- data/ini: INI files read the way Python's configparser does (interpolation off, key case kept), new code. Supports: +-- [sections], key = / key:, ; and # comments, continuation lines, top-level keys, duplicates (last wins), inline +-- comments, keys without values, typed values by option. Not supported: interpolation, DEFAULT inheritance, escapes. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,10 +21,10 @@ local Ini = { } export type DecodeOptions = { - inlineComments: boolean?, -- strip " ;..." / " #..." after values (default false, like configparser) - allowNoValue: boolean?, -- a line with a key and no delimiter is the key with value true (default false: an error) - types: boolean?, -- values that are numbers / true / false / yes / no / on / off become numbers / booleans - strict: boolean?, -- a duplicate section or key is an error (default false: last wins / merge) + inlineComments: boolean?, -- default false (configparser) + allowNoValue: boolean?, -- default false + types: boolean?, + strict: boolean?, -- default false } export type EncodeOptions = { delimiter: string?, -- default " = " @@ -92,9 +88,8 @@ function Ini.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if trimmed == "" then lastKey = nil elseif string.match(trimmed, "^[;#]") then - -- a comment line (configparser: also when indented); it does not end a continuation + -- configparser: comment lines may be indented and do not end a continuation elseif lastKey and indent > lastIndent then - -- continuation of the previous value local v = trimmed if o.inlineComments then v = string.match(v, "^(.-)%s+[;#]") or v diff --git a/src/Rosetta/data/json/init.luau b/src/Rosetta/data/json/init.luau index 8a07bb2..945d893 100644 --- a/src/Rosetta/data/json/init.luau +++ b/src/Rosetta/data/json/init.luau @@ -1,7 +1,6 @@ --!strict --- data/json: JSON (RFC 8259) files, a thin wrapper over codecs/text/Json (which see for the value mapping and options). --- Supports: decode to plain Luau values (Types.null, ordered keys and bigInts as strings by option), encode compact or --- pretty. JSON Lines through codecs/text/Json.lines. Not supported: JSON5 / comments / trailing commas. +-- data/json: JSON (RFC 8259) over codecs/text/Json. Supports: decode to Luau values, compact / pretty encode, JSON +-- Lines. Not supported: JSON5 / comments / trailing commas. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,10 +19,10 @@ local JsonFormat = { } export type DecodeOptions = Json.DecodeOptions & { - lines: boolean?, -- JSON Lines: decode every value into an array (default false: one value) + lines: boolean?, -- default false } export type EncodeOptions = Json.EncodeOptions & { - lines: boolean?, -- JSON Lines: the value must be an array, written one compact value per line + lines: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/data/msgpack/Codec.luau b/src/Rosetta/data/msgpack/Codec.luau index 93fe14c..9ba109d 100644 --- a/src/Rosetta/data/msgpack/Codec.luau +++ b/src/Rosetta/data/msgpack/Codec.luau @@ -1,7 +1,6 @@ --!strict --!native --- data/msgpack/Codec: the MessagePack decoder and encoder behind data/msgpack (msgpack spec, 2017 revision with --- str8 / bin / ext and the timestamp extension). Never throws: errors return nil, message, offset. +-- data/msgpack/Codec: MessagePack (2017 spec: str8 / bin / ext, timestamp ext -1) decoder and encoder; never throws. local Bytes = require("@rosetta/core/Bytes") local Types = require("@rosetta/Types") @@ -9,7 +8,7 @@ local Codec = {} local TWO32 = 4294967296 --- an extension value: { type = -128..127, data = buffer } +-- ext type: -128..127 local ExtMeta = { __tostring = function(e: any): string return "msgpack.ext(" .. e.type .. ", " .. buffer.len(e.data) .. " bytes)" end } @@ -20,13 +19,11 @@ function Codec.isExt(v: any): boolean return type(v) == "table" and getmetatable(v) == ExtMeta end --- decimal text of hi * 2^32 + lo (hi, lo unsigned 32-bit), exact local function u64text(hi: number, lo: number): string if hi == 0 then return string.format("%d", lo) end local digits = {} - -- long division by 10 on four 16-bit limbs local l = { hi // 65536, hi % 65536, lo // 65536, lo % 65536 } while l[1] ~= 0 or l[2] ~= 0 or l[3] ~= 0 or l[4] ~= 0 do local rem = 0 @@ -42,11 +39,11 @@ end Codec.u64text = u64text export type DecodeOptions = { - bigInts: ("number" | "string")?, -- 64-bit integers past 2^53: "string" keeps the exact decimal text - null: any?, -- the value for nil (default Types.null) - maxDepth: number?, -- nesting limit (default 512) - timestamps: boolean?, -- ext -1 as a Types.Date (default true) - ordered: boolean?, -- maps as Types.object with key order (default true) + bigInts: ("number" | "string")?, + null: any?, -- default Types.null + maxDepth: number?, -- default 512 + timestamps: boolean?, -- default true + ordered: boolean?, -- default true } type St = { r: Bytes.Reader, big: boolean, null: any, maxDepth: number, ts: boolean, ordered: boolean } @@ -55,7 +52,6 @@ local function int64(st: St, signed: boolean): any local r = st.r local hi, lo = r:u32be(), r:u32be() if signed and hi >= 0x80000000 then - -- negative: two's complement local nhi, nlo = 0xFFFFFFFF - hi, TWO32 - lo if nlo == TWO32 then nlo = 0 @@ -239,7 +235,6 @@ function value(st: St, depth: number): (any, string?) return nil, string.format("reserved type byte 0x%02x", b) end --- decode(r, opts) -> value, nil | nil, message, offset (one value; r is left after it) function Codec.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, string?, number?) local o: DecodeOptions = opts or {} local st: St = { @@ -259,11 +254,11 @@ end -- ------------------------------------------------------------------------------------------------ encode export type EncodeOptions = { - float32: boolean?, -- non-integer numbers as float32 (default false: float64) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) - emptyTable: ("array" | "map")?, -- a plain empty table (default "array") + float32: boolean?, -- default false + sortKeys: boolean?, -- default true + emptyTable: ("array" | "map")?, -- default "array" maxDepth: number?, -- default 512 (also catches cycles) - stringsAsBin: boolean?, -- strings as bin (default false: str) + stringsAsBin: boolean?, -- default false } type ESt = { w: Bytes.Writer, f32: boolean, sort: boolean, emptyMap: boolean, maxDepth: number, bin: boolean, err: string? } @@ -425,7 +420,6 @@ local function enc(st: ESt, v: any, depth: number): boolean return true end --- encode(v, opts) -> buffer | nil, message function Codec.encode(v: any, opts: EncodeOptions?): (buffer?, string?) local o: EncodeOptions = opts or {} local st: ESt = { diff --git a/src/Rosetta/data/msgpack/init.luau b/src/Rosetta/data/msgpack/init.luau index ac8183c..28b2d02 100644 --- a/src/Rosetta/data/msgpack/init.luau +++ b/src/Rosetta/data/msgpack/init.luau @@ -1,9 +1,7 @@ --!strict --- data/msgpack: MessagePack (msgpack spec, str8 / bin / ext revision). New code. Supports: every type, the --- timestamp extension (-1) as Types.Date, other extensions as Msgpack.ext(type, data), bin as buffers, maps as --- Types.object (key order kept; keys of any type), 64-bit integers past 2^53 as exact decimal strings by option, a --- stream of concatenated values (opts.all). Encode picks the smallest integer / length forms (float64 for --- non-integers unless opts.float32). Not supported: nothing in the spec. +-- data/msgpack: MessagePack (str8 / bin / ext revision), new code. Supports: every type, timestamps (ext -1) as +-- Types.Date, other ext as Msgpack.ext, exact 64-bit integers by option, concatenated streams; encode picks the +-- smallest forms. Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -21,10 +19,10 @@ local Msgpack = { } export type DecodeOptions = Codec.DecodeOptions & { - all: boolean?, -- decode every concatenated value into an array (default false: exactly one value) + all: boolean?, -- default false } export type EncodeOptions = Codec.EncodeOptions & { - all: boolean?, -- the value is an array of values, written one after another + all: boolean?, } -- ------------------------------------------------------------------------------------------------ sniff @@ -83,7 +81,6 @@ function Msgpack.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- ext(type, data) -> an extension value { type, data } that encodes as ext; isExt(v) Msgpack.ext = Codec.ext Msgpack.isExt = Codec.isExt diff --git a/src/Rosetta/data/nbt/init.luau b/src/Rosetta/data/nbt/init.luau index b78d266..e4473d9 100644 --- a/src/Rosetta/data/nbt/init.luau +++ b/src/Rosetta/data/nbt/init.luau @@ -1,10 +1,7 @@ --!strict --- data/nbt: Minecraft NBT files (.nbt structures, level.dat / playerdata .dat, servers.dat, Bedrock .mcstructure and --- level.dat), a thin format over codecs/text/Nbt (which see for the value mapping). Supports: Java big-endian and --- Bedrock little-endian NBT (the level.dat 8-byte header too; network varint NBT with opts.varint), gzip / zlib / --- uncompressed, every tag type, exact round trips (Nbt.info(value) remembers the root name, edition, compression --- and header; encode writes it back the same way unless opts say otherwise). Text SNBT: data/snbt. --- Not supported: nothing in the format. +-- data/nbt: Minecraft NBT files over codecs/text/Nbt. Supports: Java big-endian and Bedrock little-endian NBT +-- (level.dat header, varint by option), gzip / zlib / raw, every tag, exact round trips (Nbt.info). +-- Not supported: none. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -54,7 +51,7 @@ function NbtFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -NbtFormat.info = Nbt.info -- how a decoded value was stored: { name, endian, compression, header?, varint? } +NbtFormat.info = Nbt.info NbtFormat.Nbt = Nbt return NbtFormat diff --git a/src/Rosetta/data/plist/Binary.luau b/src/Rosetta/data/plist/Binary.luau index 01aec05..02dd5f1 100644 --- a/src/Rosetta/data/plist/Binary.luau +++ b/src/Rosetta/data/plist/Binary.luau @@ -1,10 +1,6 @@ --!strict --!native --- data/plist/Binary: the binary property list reader ("bplist00", CoreFoundation's format as documented in --- CFBinaryPList.c and implemented by Python's plistlib). Objects: null / bool / fill, ints (1, 2, 4, 8 bytes; 16-byte --- ints are read from their low 8 bytes), reals (4 / 8 bytes), dates, data, ASCII / UTF-16BE / UTF-8 strings, UIDs, --- arrays, sets (as arrays), dicts (Types.object, key order kept). Shared references decode to the same table; cycles --- are errors. Never throws: errors return nil, message. +-- data/plist/Binary: binary plist reader ("bplist00", CFBinaryPList.c / Python's plistlib); 16-byte ints: low 8 bytes. local Types = require("@rosetta/Types") local Binary = {} @@ -44,7 +40,6 @@ end export type Options = { bigInts: ("number" | "string")?, maxDepth: number? } --- decode(buf, base, len, opts) -> value | nil, message function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (any, string?) if len < 40 then return nil, "truncated: shorter than header + trailer" @@ -130,7 +125,6 @@ function Binary.decode(b: buffer, base: number, len: number, opts: Options?): (a if h >= 0x80000000 and nib == 3 then v = (h - TWO32) * TWO32 + l elseif opts and opts.bigInts == "string" and h >= 0x200000 then - -- exact decimal text of h * 2^32 + l local digits = {} local limbs = { h // 65536, h % 65536, l // 65536, l % 65536 } while limbs[1] + limbs[2] + limbs[3] + limbs[4] > 0 do diff --git a/src/Rosetta/data/plist/init.luau b/src/Rosetta/data/plist/init.luau index 30f68d5..bbe7867 100644 --- a/src/Rosetta/data/plist/init.luau +++ b/src/Rosetta/data/plist/init.luau @@ -1,9 +1,7 @@ --!strict --- data/plist: Apple property lists. New code. Supports: XML plists (read and write, through codecs/text/Xml; the write is --- byte-identical to Python's plistlib for the same key order) and binary plists ("bplist00", read). Values: dict -> --- Types.object (key order kept), array, string, integer / real -> number, true / false, date -> Types.Date, data -> --- buffer, UID (binary) -> Plist.uid(n). Not supported: binary write, the old OpenStep text format, integers past --- 2^63. Note: Luau has one number type, so a real with an integral value is written back as . +-- data/plist: Apple property lists, new code. Supports: XML read / write (byte-identical to Python's plistlib), +-- binary "bplist00" read, UIDs as Plist.uid. Not supported: binary write, OpenStep text, integers past 2^63; integral +-- reals write back as . -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -25,11 +23,11 @@ local Plist = { } export type DecodeOptions = { - bigInts: ("number" | "string")?, -- integers past 2^53: "string" keeps exact decimal text + bigInts: ("number" | "string")?, maxDepth: number?, -- default 512 } export type EncodeOptions = { - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keeps its order) + sortKeys: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -300,7 +298,7 @@ function Plist.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras -Plist.uid = Binary.uid -- uid(n) -> a UID value (binary plists, NSKeyedArchiver) +Plist.uid = Binary.uid Plist.isUid = Binary.isUid return Plist diff --git a/src/Rosetta/data/snbt/init.luau b/src/Rosetta/data/snbt/init.luau index af13706..1973576 100644 --- a/src/Rosetta/data/snbt/init.luau +++ b/src/Rosetta/data/snbt/init.luau @@ -1,7 +1,5 @@ --!strict --- data/snbt: stringified NBT text (Minecraft commands, datapacks, .snbt structure files), a thin format over --- codecs/text/Nbt (which see for the value mapping and grammar). Supports: parse to the same typed values data/nbt --- gives (convert between the two freely), print compact (Minecraft's form) or indented (opts.indent). +-- data/snbt: stringified NBT over codecs/text/Nbt. Supports: parse to data/nbt's values, compact or indented print. -- Not supported: the 1.21.5 bool(...) / uuid(...) operations. -- ------------------------------------------------------------------------------------------------ requires @@ -22,8 +20,8 @@ local SnbtFormat = { export type DecodeOptions = { maxDepth: number? } export type EncodeOptions = { - indent: (number | string)?, -- pretty print: spaces per level or the indent string (default: compact) - quote: string?, -- '"' (default) or "'" + indent: (number | string)?, -- default: compact + quote: string?, -- default '"' } -- ------------------------------------------------------------------------------------------------ sniff diff --git a/src/Rosetta/data/toml/Decode.luau b/src/Rosetta/data/toml/Decode.luau index 1ca6e2e..01b06fd 100644 --- a/src/Rosetta/data/toml/Decode.luau +++ b/src/Rosetta/data/toml/Decode.luau @@ -1,8 +1,5 @@ --!strict --- data/toml/Decode: the TOML 1.0.0 parser behind data/toml. Tables (and inline tables) are Types.object values with --- their key order; arrays are arrays; datetimes are Types.Date values. Checks the 1.0 validity rules: UTF-8, control --- characters, table / key redefinition (explicit, implicit, dotted, inline and array-of-tables), number grammar and --- 64-bit range, escapes, datetimes. Never throws: failures return nil, message, offset (0-based). +-- data/toml/Decode: TOML 1.0.0 parser with the 1.0 validity rules; never throws (nil, message, 0-based offset). local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") @@ -11,7 +8,7 @@ local Decode = {} local byte, sub, find, match, gsub, char = string.byte, string.sub, string.find, string.match, string.gsub, string.char export type Options = { - bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their digits (default "number") + bigInts: ("number" | "string")?, -- default "number" } local utf8char = Text.utf8char @@ -32,7 +29,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return nil end - -- input checks: BOM, UTF-8, control characters, bare CR if sub(s, 1, 3) == "\239\187\191" then s = sub(s, 4) end @@ -80,7 +76,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) local function ws(i: number): number return match(s, "^[ \t]*()", i) :: any end - -- whitespace, newlines and comments (inside arrays) local function wsnl(i: number): number while true do i = match(s, "^[ \t\n]*()", i) :: any @@ -114,7 +109,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return fail("bad escape", p) end - -- strings: value, next | nil local function basic(i: number): (string?, number) local parts = {} local j = i + 1 @@ -204,7 +198,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) return sub(s, j, e - 1) .. string.rep("'", extra), q end - -- a (dotted) key: { parts }, next | nil local function key(i: number): ({ string }?, number) local keys: { string } = {} while true do @@ -242,7 +235,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end end - -- numbers and datetimes local function number(i: number): (any, number) local tok = match(s, "^[%+%-]?[%w_%.]+", i) if not tok then @@ -556,7 +548,6 @@ function Decode.decode(s: string, opts: Options?): (any, any, number?) end ni += 1 end - -- walk to the parent local t = root for j = 1, #keys - 1 do local k = keys[j] diff --git a/src/Rosetta/data/toml/Encode.luau b/src/Rosetta/data/toml/Encode.luau index 3652827..679bc28 100644 --- a/src/Rosetta/data/toml/Encode.luau +++ b/src/Rosetta/data/toml/Encode.luau @@ -1,9 +1,5 @@ --!strict --- data/toml/Encode: the TOML 1.0.0 writer behind data/toml. A table's plain values come first, then its sub-tables --- as [a.b] sections and arrays of tables as [[a.b]]; keys in Types.object order (plain tables: sorted); strings as --- basic strings with escapes; numbers as integers when integral (|x| < 2^63) else round-trip float text; Types.Date --- values as datetimes. Never throws: bad values (null, buffers, functions, cycles, non-string keys) return nil, --- message. +-- data/toml/Encode: TOML 1.0.0 writer: plain values, then [a.b] sections and [[a.b]] arrays of tables; never throws. local Types = require("@rosetta/Types") local Json = require("@rosetta/codecs/text/Json") @@ -12,8 +8,8 @@ local Encode = {} local format, gsub, find = string.format, string.gsub, string.find export type Options = { - inline: boolean?, -- write every sub-table as an inline table (default false: [sections]) - indent: (number | string)?, -- indent keys of nested sections (default none) + inline: boolean?, -- default false + indent: (number | string)?, -- default none } local ESC: { [string]: string } = { ['"'] = '\\"', ["\\"] = "\\\\", ["\b"] = "\\b", ["\t"] = "\\t", ["\n"] = "\\n", ["\f"] = "\\f", ["\r"] = "\\r", ["\127"] = "\\u007F" } @@ -36,7 +32,6 @@ local function keyText(k: string): string return quote(k) end --- isMap(t): a table written as a TOML table (Types.object, or keys other than 1..n); empty plain tables are arrays local function isMap(t: { [any]: any }): boolean if Types.isObject(t) then return true @@ -56,7 +51,6 @@ local function isDate(v: any): boolean return Types.Date.is(v) end --- an array of tables: non-empty, every element a map local function isAot(v: any): boolean if type(v) ~= "table" or isDate(v) or isMap(v) or #v == 0 then return false @@ -196,7 +190,6 @@ local function section(st: State, t: any, path: string, out: { string }, inlineA return true end --- encode(t, opts) -> text | nil, message function Encode.encode(t: any, opts: Options?): (string?, string?) if type(t) ~= "table" or isDate(t) or (not isMap(t) and next(t) ~= nil) then return nil, "the top level must be a table with string keys" diff --git a/src/Rosetta/data/toml/init.luau b/src/Rosetta/data/toml/init.luau index 9977ad1..0b1db54 100644 --- a/src/Rosetta/data/toml/init.luau +++ b/src/Rosetta/data/toml/init.luau @@ -1,11 +1,7 @@ --!strict --- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0). New code. Supports: decode of the whole 1.0 grammar (tables, --- inline tables, arrays of tables, dotted keys, every string kind, integers in every base with the 64-bit range --- check, floats incl. inf / nan, booleans, offset / local datetimes, local dates and times) with the validity rules --- (redefinitions, UTF-8, control characters, number grammar), tested against toml-test; encode from plain tables / --- Types.object (key order kept) / Types.Date. Tables decode to Types.object values (key order kept), datetimes to --- Types.Date. Not supported: TOML 1.1 additions; the integer / float distinction is lost (Luau numbers: integral --- values are written as integers). +-- data/toml: TOML 1.0.0 (https://toml.io/en/v1.0.0), new code, tested against toml-test. Supports: the whole 1.0 +-- grammar and validity rules; tables as Types.object, datetimes as Types.Date. Not supported: TOML 1.1; the integer / +-- float distinction (integral values write as integers). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,8 +23,7 @@ export type DecodeOptions = Decode.Options export type EncodeOptions = Encode.Options -- ------------------------------------------------------------------------------------------------ sniff --- text that starts (after comments / blank lines) with a [table] header or a key = value line; INI looks the same, --- so this stays low and the extension decides +-- INI looks the same: a [table] or key = value start scores low and the extension decides function Toml.sniff(r: Bytes.Reader): number local head = r:peek(512) if string.find(head, "%z") then diff --git a/src/Rosetta/data/xml/init.luau b/src/Rosetta/data/xml/init.luau index b493ce1..d3f8004 100644 --- a/src/Rosetta/data/xml/init.luau +++ b/src/Rosetta/data/xml/init.luau @@ -1,7 +1,6 @@ --!strict --- data/xml: XML 1.0 files, a thin wrapper over codecs/text/Xml (which see for the node shape and options). Supports: --- decode to a "#document" XmlNode tree (doc.root = the root element), encode a document or an element. Not --- supported: external entities / DTDs, validation. +-- data/xml: XML 1.0 over codecs/text/Xml. Supports: decode to a "#document" XmlNode tree, encode a document or an +-- element. Not supported: external entities / DTDs, validation. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") diff --git a/src/Rosetta/data/yaml/Emit.luau b/src/Rosetta/data/yaml/Emit.luau index c46d2fd..b01a1c4 100644 --- a/src/Rosetta/data/yaml/Emit.luau +++ b/src/Rosetta/data/yaml/Emit.luau @@ -1,9 +1,5 @@ --!strict --- data/yaml/Emit: the YAML writer behind data/yaml. Block style; empty collections as [] / {}; strings plain when --- they read back as the same string (core schema, and not a YAML 1.1 boolean like "yes"), literal block scalars --- for multi-line text, double-quoted otherwise; numbers with the shortest round-trip text, .inf / .nan; buffers as --- !!binary; dates as their RFC 3339 text; tables referenced twice get an anchor and aliases. Never throws: bad --- values (cycles, functions, collection keys) return nil, message. +-- data/yaml/Emit: YAML block-style writer; plain scalars only when they read back the same (core schema, no 1.1 bools). local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") local Parse = require("@rosetta/data/yaml/Parse") @@ -11,11 +7,11 @@ local Parse = require("@rosetta/data/yaml/Parse") local Emit = {} export type Options = { - indent: number?, -- spaces per level (default 2) - all: boolean?, -- the value is an array of documents, written with "---" separators - explicitStart: boolean?, -- start the (first) document with "---" (default false) - sortKeys: boolean?, -- plain tables' keys sorted (default true; Types.object keys keep their order) - null: any?, -- the value written as null besides Types.null + indent: number?, -- default 2 + all: boolean?, + explicitStart: boolean?, -- default false + sortKeys: boolean?, -- default true + null: any?, } local format, byte, find, gsub = string.format, string.byte, string.find, string.gsub @@ -96,7 +92,6 @@ local function plainOk(s: string): boolean return true end --- a string as a scalar on a line at indentation ind (for block scalars) local function str(s: string, ind: string, key: boolean): string if plainOk(s) then return s @@ -126,7 +121,6 @@ local keyLess = Types.keyLess type St = { out: { string }, step: number, sort: boolean, null: any, refs: { [any]: number }, anchors: { [any]: string }, nextId: number, err: string? } --- count references to tables (anchors for those seen twice); false on a cycle local function count(st: St, v: any, onStack: { [any]: boolean }): boolean if type(v) ~= "table" or v == Types.null or v == st.null or Types.Date.is(v) then return true @@ -150,7 +144,6 @@ local function count(st: St, v: any, onStack: { [any]: boolean }): boolean return true end --- scalar text for a non-collection value, or nil local function scalar(st: St, v: any, ind: string, key: boolean): string? local tv = type(v) if v == nil or v == Types.null or (st.null ~= nil and v == st.null) then @@ -171,7 +164,6 @@ end local write: (st: St, v: any, depth: number) -> string? --- the text of v as a node whose first line follows "key:" / "- " (it starts with a space or a newline) function write(st: St, v: any, depth: number): string? local ind = string.rep(" ", st.step * (depth + 1)) local s = scalar(st, v, ind, false) @@ -244,19 +236,16 @@ local function document(st: St, v: any): string? if not t then return nil end - -- the top level: drop the separator write() put before the first line if string.sub(t, 1, 1) == "\n" then return string.sub(t, 2) end local body = string.sub(t, 2) if string.sub(body, 1, 1) == "&" then - -- "&id001\n- a": an anchored top-level collection return body end return body end --- encode(v, opts) -> text | nil, message function Emit.encode(v: any, opts: Options?): (string?, string?) local o: Options = opts or {} local st: St = { diff --git a/src/Rosetta/data/yaml/Parse.luau b/src/Rosetta/data/yaml/Parse.luau index 425d08e..fdcf2e5 100644 --- a/src/Rosetta/data/yaml/Parse.luau +++ b/src/Rosetta/data/yaml/Parse.luau @@ -1,11 +1,5 @@ --!strict --- data/yaml/Parse: the YAML 1.2 parser behind data/yaml. Recursive descent over the text (line breaks normalized): --- block mappings / sequences (compact forms included), flow collections, plain / single / double-quoted scalars with --- line folding, literal / folded block scalars (indentation and chomping indicators), anchors and aliases (shared --- references, with an expansion-size limit), tags (core types + !!binary, !!timestamp; others UNSUPPORTED unless --- opts.tags = "ignore"), %YAML / %TAG directives, multi-document streams, comments. Scalars resolve with the core --- schema. Not supported: complex keys ("? "), collections as keys, recursive aliases, merge keys "<<" (kept as a --- normal key). Internally raises { yamlErr } tables caught by run(); never throws past it. +-- data/yaml/Parse: YAML 1.2 recursive-descent parser; raises { yamlErr } tables caught by run(), never throws past it. local Text = require("@rosetta/codecs/text/Text") local Types = require("@rosetta/Types") local Base64 = require("@rosetta/core/Base64") @@ -15,11 +9,11 @@ local Parse = {} local byte, sub, find, match, char = string.byte, string.sub, string.find, string.match, string.char export type Options = { - all: boolean?, -- every document as an array (default false: the first document; none -> Types.null) - tags: ("error" | "ignore")?, -- unknown tags: an UNSUPPORTED error (default) or resolved as if untagged - maxAliasNodes: number?, -- the total size of aliased nodes (default 1e6): the billion laughs guard - maxDepth: number?, -- nesting limit (default 500) - null: any?, -- the value for null (default Types.null) + all: boolean?, -- default false + tags: ("error" | "ignore")?, -- default "error" + maxAliasNodes: number?, -- default 1e6 (billion laughs guard) + maxDepth: number?, -- default 500 + null: any?, -- default Types.null } type St = { @@ -54,7 +48,7 @@ local function col(s: string, p: number): number return p - q end -local function isWsEnd(c: number?): boolean -- space, tab, newline or the end +local function isWsEnd(c: number?): boolean return c == nil or c == 32 or c == 9 or c == 10 end @@ -66,7 +60,6 @@ local function docMarker(s: string, p: number): boolean return (m == "---" or m == "...") and isWsEnd(byte(s, p + 3)) end --- skip spaces, tabs, comments and line breaks: the next content position (n + 1 at the end) local function skip(s: string, p: number): number local n = #s while p <= n do @@ -86,7 +79,6 @@ local function skip(s: string, p: number): number return p end --- the number of leading spaces on p's line, and whether a tab comes before p on it local function lineIndent(s: string, p: number): (number, boolean) local q = p while q > 1 and byte(s, q - 1) ~= 10 do @@ -105,7 +97,6 @@ local function noTabs(s: string, p: number, ind: number?) end end --- skip spaces / tabs on the line local function skipLine(s: string, p: number): number return match(s, "^[ \t]*()", p) :: any end @@ -120,7 +111,6 @@ end local utf8char = Text.utf8char -- ------------------------------------------------------------------------------------------------ resolution --- the core schema: a plain scalar's value function Parse.resolve(t: string, nullv: any): any if t == "" or t == "~" or t == "null" or t == "Null" or t == "NULL" then return nullv @@ -168,7 +158,6 @@ local function base64(t: string): buffer? return (Base64.decode(t)) end --- a scalar's value given its tag (nil = untagged, "!" = non-specific) local function scalarValue(st: St, raw: string, plain: boolean, tag: string?, p: number): any if tag == nil then return if plain then Parse.resolve(raw, st.null) else raw @@ -237,7 +226,6 @@ local function collectionTag(st: St, tag: string?, kind: string, p: number) end end --- expansion size of a value (nodes), memoized local function size(st: St, v: any): number if type(v) ~= "table" or v == st.null then return 1 @@ -257,7 +245,6 @@ end -- ------------------------------------------------------------------------------------------------ properties type Props = { anchor: string?, tag: string?, at: number } --- anchors / tags at p -> props?, the position after them (and the spaces after them) local function properties(st: St, p: number): (Props?, number) local s = st.s local props: Props? = nil @@ -348,8 +335,7 @@ local function alias(st: St, p: number): (any, number) end -- ------------------------------------------------------------------------------------------------ scalars --- fold the line break(s) at p (p at a '\n'): the text they become and the position of the next line's content. --- Lines holding only spaces / tabs count as empty. +-- line folding: lines holding only spaces / tabs count as empty local function fold(s: string, p: number): (string, number) local empties = 0 local q = p + 1 @@ -385,7 +371,6 @@ local ESC: { [number]: string } = { [80] = "\226\128\169", } --- a quoted scalar at p ('"' or "'") -> text, the position after the closing quote local function quoted(st: St, p: number, ind: number): (string, number) local s = st.s local dq = byte(s, p) == 34 @@ -456,15 +441,13 @@ local function quoted(st: St, p: number, ind: number): (string, number) end end --- a plain scalar at p -> text, the position after it. ind: continuation lines must be indented deeper than ind --- (block context); flow: the flow-context rules (stops at , [ ] { }). +-- plain scalar: continuation lines indented deeper than ind (block context); flow context stops at , [ ] { } local function plain(st: St, p: number, ind: number, flow: boolean): (string, number) local s = st.s local parts: { string } = {} local i = p local lastEnd = p while true do - -- one line's worth local j = i local stopAt = nil while true do @@ -492,7 +475,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu if stopAt or byte(s, j) == nil then return table.concat(parts), lastEnd end - -- a continuation line? local f, q = fold(s, j) local r = skipLine(s, q) local c = byte(s, r) @@ -507,7 +489,6 @@ local function plain(st: St, p: number, ind: number, flow: boolean): (string, nu end end --- a block scalar at p ('|' or '>'); ind = the parent's indentation -> text, the position after it local function blockScalar(st: St, p: number, ind: number): (string, number) local s = st.s local folded = byte(s, p) == 62 @@ -529,7 +510,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) end local nl = find(s, "\n", q, true) local lines: { string } = {} - local trailing = 0 -- empty lines after the last content line + local trailing = 0 if not nl then return "", #s + 1 end @@ -568,7 +549,6 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) indent = ind + 1 end end - -- the lines local r = ls local pendingEmpty = 0 local endPos = ls @@ -625,7 +605,7 @@ local function blockScalar(st: St, p: number, ind: number): (string, number) empties = 0 end end - trailing += empties -- empty lines after the last content line (or all of them) + trailing += empties body = table.concat(out) end if not folded then @@ -666,7 +646,6 @@ local function enter(st: St, p: number) end end --- a flow node at p (after skip) -> value, next, wasEmpty local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local s = st.s local props, q = properties(st, p) @@ -688,7 +667,6 @@ local function flowNode(st: St, p: number, ind: number): (any, number, boolean) local t, r = quoted(st, q, ind) return finish(st, props, scalarValue(st, t, false, props and props.tag, q)), r, false elseif c == nil or c == 44 or c == 93 or c == 125 or (c == 58 and (isWsEnd(byte(s, q + 1)) or byte(s, q + 1) == 44 or byte(s, q + 1) == 93 or byte(s, q + 1) == 125)) then - -- an empty node return finish(st, props, scalarValue(st, "", true, props and props.tag, q)), (if props then q else p), true elseif c == 35 or c == 38 or c == 33 or c == 124 or c == 62 or c == 37 or c == 64 or c == 96 then corrupt("unexpected character in a flow collection", q) @@ -819,7 +797,7 @@ end -- ------------------------------------------------------------------------------------------------ block local blockNode: (st: St, ind: number, p: number, inline: boolean, mapParent: boolean) -> (any, number) --- an implicit key at p (on one line, followed by ':' and a space / the end of the line) -> key, position after ':' +-- implicit key: on one line, followed by ':' and a space or the end of the line local function implicitKey(st: St, p: number): (any, number?) local s = st.s local c = byte(s, p) @@ -847,7 +825,6 @@ local function implicitKey(st: St, p: number): (any, number?) end return nil, nil elseif c == 91 or c == 123 then - -- a flow collection used as a key? local e = find(s, "\n", p, true) or #s + 1 local line = sub(s, p, e - 1) if match(line, "[%]}]%s*:%s") or match(line, "[%]}]%s*:$") then @@ -892,7 +869,7 @@ local function readKey(st: St, p: number, props: Props?): (any, number) end k, q = alias(st, p) q = skipLine(s, q) - q += 1 -- the ':' + q += 1 elseif c == 34 or c == 39 then local t, r = quoted(st, p, -1) if find(sub(s, p, r - 1), "\n", 1, true) then @@ -912,7 +889,6 @@ local function readKey(st: St, p: number, props: Props?): (any, number) return checkKey(st, k, p), q end --- a node on the lines after p's line (content deeper than ind; or a sequence at ind when seqAt) -> value, next | null local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapParent: boolean): (any, number) local s = st.s local r = skip(s, p) @@ -926,7 +902,6 @@ local function nextLineNode(st: St, ind: number, p: number, seqAt: boolean, mapP return st.null, p end --- the value after a ':' (at p, just past it) of a mapping at column mc local function mapValue(st: St, mc: number, p: number, explicit: boolean): (any, number) local s = st.s local r = skipLine(s, p) @@ -1044,7 +1019,6 @@ local function blockSeq(st: St, sc: number, p: number): (any, number) return t, q end --- the node at q after its properties (props may be nil); start = where the properties began local function afterProps(st: St, ind: number, start: number, q: number, props: Props?, inline: boolean, mapParent: boolean): (any, number) local s = st.s local tag = props and props.tag @@ -1111,9 +1085,6 @@ local function afterProps(st: St, ind: number, start: number, q: number, props: return finish(st, props, scalarValue(st, text, true, tag, q)), e end --- a block node at p (content; col(p) > ind, or == ind for a sequence that is a mapping's value). inline: on the --- same line as its mapping key (no new block collection may start). mapParent: a sequence at the parent's --- indentation may follow properties that end their line. function blockNode(st: St, ind: number, p: number, inline: boolean, mapParent: boolean): (any, number) local s = st.s local props, q = properties(st, p) @@ -1253,7 +1224,6 @@ local function stream(st: St): { any } p = q else if explicit and not find(sub(s, p, q), "\n", 1, true) then - -- content on the "---" line local ok, _, q2 = pcall(properties, st, q) local c = byte(s, q2) if ok and c ~= 124 and c ~= 62 and not endOfLine(s, q2) and implicitKey(st, q2) ~= nil then @@ -1282,7 +1252,6 @@ local function stream(st: St): { any } return docs end --- run(text, opts) -> docs | nil, code, message, offset function Parse.run(text: string, opts: Options?): (any, any, any, any) local o: Options = opts or {} local s = text diff --git a/src/Rosetta/data/yaml/init.luau b/src/Rosetta/data/yaml/init.luau index 7c6c355..53ac771 100644 --- a/src/Rosetta/data/yaml/init.luau +++ b/src/Rosetta/data/yaml/init.luau @@ -1,11 +1,7 @@ --!strict --- data/yaml: YAML 1.2 (core schema), new code. Supports: block and flow styles, compact nested collections, plain / --- quoted / literal / folded scalars (indentation and chomping indicators), comments, anchors and aliases (decoded as --- shared references; an expansion-size limit guards against alias bombs), tags !!str !!int !!float !!bool !!null --- !!map !!seq !!binary (-> buffer) !!timestamp (-> Types.Date) and verbatim / %TAG forms, multi-document streams. --- Maps decode to Types.object (key order kept), null to Types.null. Writes block style (anchors for shared tables). --- Not supported (Err.UNSUPPORTED): complex keys "? ", collections as keys, other tags unless opts.tags = "ignore"; --- merge keys "<<" stay ordinary keys; YAML 1.1 types (yes / no, sexagesimal, ...) are strings. +-- data/yaml: YAML 1.2 (core schema), new code. Supports: block / flow styles, every scalar style, anchors and aliases +-- (shared, alias-bomb limit), core tags + !!binary / !!timestamp, %TAG, multi-document streams; writes block style. +-- Not supported (Err.UNSUPPORTED): complex keys, collections as keys; merge keys stay keys; YAML 1.1 types are strings. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -47,7 +43,6 @@ function Yaml.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- decode(r, opts?) -> the first document (Types.null when there is none) | every document (opts.all) | nil, Err function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local text = buffer.readstring(r.buf, r.base, r.limit - r.base) local docs, code, msg, at = Parse.run(text, opts) @@ -65,7 +60,6 @@ function Yaml.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode --- encode(value, opts?) -> buffer | nil, Err (opts.all: value is an array of documents) function Yaml.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local s, err = Emit.encode(value, opts) if not s then diff --git a/src/Rosetta/font/bdf/init.luau b/src/Rosetta/font/bdf/init.luau index b63322e..8c0a38f 100644 --- a/src/Rosetta/font/bdf/init.luau +++ b/src/Rosetta/font/bdf/init.luau @@ -1,13 +1,7 @@ --!strict --- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0) bitmap fonts, read and written, as the --- standard Font with a bitmap strike (codecs/font/Bitmap): FONT / SIZE / FONTBOUNDINGBOX, the properties (all kept in --- meta.properties; FONT_ASCENT / FONT_DESCENT / PIXEL_SIZE / DEFAULT_CHAR / FAMILY_NAME / WEIGHT_NAME / SLANT used), --- glyphs with STARTCHAR names, ENCODING (-1 for unencoded, "-1 n" non-standard codes), DWIDTH / BBX (falling back to --- the font's) and hex BITMAP rows. Code points: ENCODING is the Unicode code point for CHARSET_REGISTRY ISO10646, for --- ISO8859-1 and for fonts without a registry; fonts in other charsets keep their glyphs unmapped (glyph names and --- meta.encodings keep the codes). Writing takes any Font (Bitmap.strike: a bitmap font as it is, an outline font --- rasterized at opts.px) and writes Unicode (ISO10646-1) BDF 2.1. Written from Adobe's BDF 2.1 specification. --- Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR are read and ignored). +-- font/bdf: Glyph Bitmap Distribution Format 2.1 (and 2.2's METRICSSET 0), read and written, from Adobe's BDF 2.1 +-- spec. ENCODING is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets stay unmapped. Writes +-- Unicode (ISO10646-1) BDF 2.1 from any Font. Not supported: vertical metrics (SWIDTH1 / DWIDTH1 / VVECTOR ignored). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -27,9 +21,9 @@ local Bdf = { export type DecodeOptions = { maxGlyphs: number? } -- default 1114112 export type EncodeOptions = { - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - name: string?, -- the FONT (XLFD) name (default built from the font's family / style) + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + name: string?, -- XLFD; default built from the family / style } -- ------------------------------------------------------------------------------------------------ sniff @@ -223,7 +217,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local bold = string.find(string.lower(tostring(info.style or "")), "bold") ~= nil local italic = string.find(string.lower(tostring(info.style or "")), "italic") ~= nil local px = strike.size - -- the font bounding box local x0, y0, x1, y1 = math.huge, math.huge, -math.huge, -math.huge for _, g in strike.glyphs do if g.width > 0 and g.height > 0 then @@ -244,7 +237,6 @@ function Bdf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) string.format("SIZE %d 75 75", px), string.format("FONTBOUNDINGBOX %d %d %d %d", x1 - x0, y1 - y0, x0, y0), } - -- the default glyph: the strike's default, else glyph 0 local defaultIndex = (strike.default or 0) + 1 local props: { { any } } = { { "FAMILY_NAME", quote(family) }, diff --git a/src/Rosetta/font/bmfont/Parse.luau b/src/Rosetta/font/bmfont/Parse.luau index d4a0076..2b8d8e4 100644 --- a/src/Rosetta/font/bmfont/Parse.luau +++ b/src/Rosetta/font/bmfont/Parse.luau @@ -1,10 +1,5 @@ --!strict --- font/bmfont/Parse: the three AngelCode BMFont descriptor encodings (text, XML, binary version 3) to and from one --- description table { info, common, pages, chars, kernings }. Written from the BMFont documentation --- (angelcode.com/products/bmfont/doc/file_format.html). The XML reader only scans elements and attributes (the --- descriptor has no nesting that matters, no text content). --- --- Never throws on bad input: parse functions return nil, message. +-- font/bmfont/Parse: BMFont text / XML / binary v3 descriptors (angelcode.com/products/bmfont/doc/file_format.html). local Bytes = require("@rosetta/core/Bytes") local Parse = {} @@ -24,12 +19,12 @@ export type Char = { export type Desc = { info: { [string]: any }, -- face, size, bold, italic, charset, unicode, stretchH, smooth, aa, padding {4}, spacing {2}, outline common: { [string]: any }, -- lineHeight, base, scaleW, scaleH, pages, packed, alphaChnl, redChnl, greenChnl, blueChnl - pages: { string }, -- file names, by page id (1-based: page id 0 is pages[1]) + pages: { string }, -- by page id: page id 0 is pages[1] chars: { Char }, kernings: { { number } }, -- { first, second, amount } } -local LIMIT = 1000000 -- chars / kernings +local LIMIT = 1000000 local INFO_NUM = { "size", "bold", "italic", "unicode", "stretchH", "smooth", "aa", "outline" } local COMMON_NUM = { "lineHeight", "base", "scaleW", "scaleH", "pages", "packed", "alphaChnl", "redChnl", "greenChnl", "blueChnl" } @@ -54,7 +49,6 @@ local function new(): Desc return { info = {}, common = {}, pages = {}, chars = {}, kernings = {} } end --- one tag's attributes (already split into key -> string) into the description local function apply(d: Desc, tag: string, a: { [string]: string }): string? if tag == "info" then d.info.face = a.face or "" diff --git a/src/Rosetta/font/bmfont/init.luau b/src/Rosetta/font/bmfont/init.luau index 617c9fa..2049d5e 100644 --- a/src/Rosetta/font/bmfont/init.luau +++ b/src/Rosetta/font/bmfont/init.luau @@ -1,11 +1,7 @@ --!strict --- font/bmfont: AngelCode BMFont descriptors (.fnt) in all three encodings: text, XML and binary (version 3), read and --- written. Decodes to the standard Font (a bitmap font: glyphIndex / advance / kern work, outline is nil, rasterize --- crops the glyph from its page as alpha8). Pages are image files named by the descriptor (meta.pageFiles); they are --- loaded lazily through font:loadPages(loader) or the loader the api attaches (opts.loadPage(file) -> Image, or the --- files next to the .fnt on hosts with a file system). Bmfont.bake(font, opts) renders any outline Font (ttf / otf / --- woff) into a packed bitmap font with its pages. Written from the BMFont documentation. --- Not supported: packed multi-channel glyphs (chnl other than one channel or all: read as alpha). +-- font/bmfont: AngelCode BMFont descriptors (.fnt: text, XML, binary version 3), read and written, from the BMFont +-- documentation. Pages are image files (meta.pageFiles), loaded lazily; Bmfont.bake renders an outline Font to pages. +-- Not supported: packed multi-channel glyphs (read as alpha). -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,25 +20,24 @@ local Bmfont = { } export type DecodeOptions = { - pages: { Types.Image }?, -- the page images, if the caller has them already (page id 0 first) - loadPage: ((file: string, page: number) -> any)?, -- loader for lazy pages: file -> Image (the api passes one) + pages: { Types.Image }?, -- page id 0 first + loadPage: ((file: string, page: number) -> any)?, } export type EncodeOptions = { variant: ("text" | "xml" | "binary")?, -- default: the variant it was read from, else "text" - px: number?, -- fonts without a BMFont description are baked first (see bake) + px: number?, chars: (string | { number })?, - file: string?, -- baking: the page file name prefix (default: opts.name without its extension, else "font") - name: string?, -- the destination's file name (set by the api) - files: { [string]: any }?, -- the page images are written here, encoded by opts.encodeImage (the api passes - -- both): files[page file name] = PNG bytes, for the baked pages or a BMFont's loaded pages + file: string?, -- default: opts.name without its extension, else "font" + name: string?, + files: { [string]: any }?, encodeImage: ((img: any, format: string) -> (buffer?, any))?, } export type BakeOptions = { - px: number?, -- pixels per em (default 32) - chars: (string | { number })?, -- code points to include (default printable ASCII 32..126) - pageSize: number?, -- page width = height (default: the smallest power of two that fits, up to 4096) - padding: number?, -- empty pixels around each glyph (default 1) - file: string?, -- page file name prefix (default "font"): pages are _.png + px: number?, -- default 32 + chars: (string | { number })?, -- default printable ASCII 32..126 + pageSize: number?, -- default: the smallest power of two that fits, up to 4096 + padding: number?, -- default 1 + file: string?, -- default "font"; pages are _.png } -- ------------------------------------------------------------------------------------------------ sniff @@ -61,7 +56,6 @@ function Bmfont.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the Font value local Face = {} Face.__index = Face @@ -80,10 +74,9 @@ function Face.kern(self: any, a: number, b: number): number return self._kern[ca.id * 2097152 + cb.id] or 0 end function Face.outline(_self: any, _g: number): { any }? - return nil -- bitmap font + return nil end --- loadPages(loader?) -> true | nil, Err: loader(file, pageIndex) -> Image (rgba8) | nil function Face.loadPages(self: any, loader: any?): (boolean?, Err.Err?) local load = loader or self.meta.pageLoader if type(load) ~= "function" then @@ -103,8 +96,6 @@ end local CHANNEL = { [1] = 2, [2] = 1, [4] = 0, [8] = 3 } -- chnl bit -> byte in rgba8 --- rasterize(g, px?) -> alpha8 Image cropped from the glyph's page (px is ignored: bitmap fonts have one size; --- meta.scale = px / size tells the caller how much to scale). nil when the pages are not loaded / available. function Face.rasterize(self: any, g: number, px: number?): Types.Image? local c = self._chars[g] if not c then @@ -141,7 +132,6 @@ function Face.rasterize(self: any, g: number, px: number?): Types.Image? return img end --- the Font value of a description local function face(d: Parse.Desc, variant: string): any local f: any = setmetatable({ kind = "font", @@ -244,7 +234,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) local d = type(font.meta) == "table" and font.meta.bmfont or nil local pages = font.pages if d == nil then - -- page names: opts.file, else the destination's base name (the api passes opts.name), else "font" local file = opts and opts.file if file == nil and opts and type(opts.name) == "string" then file = string.match(opts.name, "([^/\\]-)%.[^./\\]*$") or string.match(opts.name, "([^/\\]+)$") @@ -262,7 +251,6 @@ function Bmfont.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if not validDesc(d) then return nil, Err.new(Err.ARG, "bad BMFont description in font.meta.bmfont") end - -- the page images into opts.files, under the names the descriptor gives them local files = opts and opts.files local encodeImage = opts and opts.encodeImage if type(files) == "table" and type(encodeImage) == "function" and type(pages) == "table" then @@ -310,9 +298,6 @@ local function codepoints(chars: any): { number } return out end --- bake(font, opts?) -> a BMFont Font (pages: rgba8 Images, white with the coverage as alpha) | nil, Err. Glyphs are --- rasterized with font:rasterize and packed in rows (tallest first); kerning pairs between the baked characters are --- kept (rounded to pixels). function Bmfont.bake(font: any, opts: BakeOptions?): (any, Err.Err?) if type(font) ~= "table" or type(font.rasterize) ~= "function" or type(font.glyphIndex) ~= "function" then return nil, Err.new(Err.ARG, "bake: expected an outline Font") diff --git a/src/Rosetta/font/eot/init.luau b/src/Rosetta/font/eot/init.luau index e3e9bc4..83ecdc1 100644 --- a/src/Rosetta/font/eot/init.luau +++ b/src/Rosetta/font/eot/init.luau @@ -1,10 +1,7 @@ --!strict --- font/eot: Embedded OpenType (.eot; versions 0x00010000, 0x00020001 and 0x00020002): the EOT header (PANOSE, charset, --- weight, fsType, Unicode / code page ranges, family / style / version / full names, the root string, EUDC data) and --- the font data inside, XOR-0x50 obfuscated or not, read as the standard Font through codecs/font/TrueType (meta.eot --- holds the header fields, meta.fontData the TrueType bytes). Writes EOT 2.1 around TrueType bytes (a buffer / string, --- or a Font read from an EOT), filling the header from the font's OS/2, head and name tables. Written from the W3C --- EOT submission (2008). Not supported: MicroType Express compressed fonts (flag 0x4: Err.UNSUPPORTED), signatures. +-- font/eot: Embedded OpenType (versions 0x00010000, 0x00020001, 0x00020002; W3C EOT submission, 2008): the header +-- and the font data (XOR-0x50 obfuscated or not) through codecs/font/TrueType; writes EOT 2.1 around TrueType bytes. +-- Not supported: MicroType Express compression (flag 0x4: Err.UNSUPPORTED), signatures. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -24,8 +21,8 @@ local Eot = { export type DecodeOptions = {} export type EncodeOptions = { - xor: boolean?, -- obfuscate the font data with XOR 0x50 (default false) - rootString: string?, -- the URLs allowed to use the font (default "") + xor: boolean?, -- XOR 0x50; default false + rootString: string?, -- default "" } -- ------------------------------------------------------------------------------------------------ constants diff --git a/src/Rosetta/font/fon/init.luau b/src/Rosetta/font/fon/init.luau index b4bef4d..ab869d1 100644 --- a/src/Rosetta/font/fon/init.luau +++ b/src/Rosetta/font/fon/init.luau @@ -1,10 +1,6 @@ --!strict --- font/fon: Windows raster fonts: bare .fnt resources (versions 2.0 and 3.0: the header, the character table and the --- column-major glyph bitmaps) and .fon files holding them as RT_FONT resources of a 16-bit NE executable (or a PE --- one), as the standard Font with a bitmap strike (codecs/font/Bitmap). A .fon usually holds several sizes: the first --- (or the one closest to opts.size pixels) is the Font, every strike's Font is in meta.strikes. Code points: ANSI --- charset fonts map through Windows-1252, other charsets keep their byte codes below 0x80 only (meta.charset). --- Written from Microsoft's "Windows 3.0 font file format" (KB65123) and the NE / PE resource table layouts. +-- font/fon: Windows raster fonts: .fnt resources (versions 2.0 / 3.0) and .fon NE / PE executables holding them as +-- RT_FONT, from Microsoft's KB65123 and the NE / PE resource layouts; ANSI charset maps through Windows-1252. -- Not supported: vector FNT (Err.UNSUPPORTED), writing. -- ------------------------------------------------------------------------------------------------ requires @@ -24,7 +20,7 @@ local Fon = { caps = { decode = true, encode = false, bitmap = true, variants = { "fnt2", "fnt3", "ne", "pe" } }, } -export type DecodeOptions = { size: number? } -- pick the strike closest to this pixel height (default: the first) +export type DecodeOptions = { size: number? } -- default: the first strike -- ------------------------------------------------------------------------------------------------ sniff local function isFnt(h: string): boolean @@ -50,7 +46,6 @@ function Fon.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- one FNT resource -> Font local function fnt(r: Bytes.Reader): (any, Err.Err?) local version = r:u16le() local total = r:u32le() @@ -145,7 +140,6 @@ local function fnt(r: Bytes.Reader): (any, Err.Err?) }), nil end --- the RT_FONT resources of an NE executable: { { offset, length } } local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) local rt = r:sub(ne + 0x24, 2):u16le() local t = r:sub(ne + rt) @@ -175,7 +169,7 @@ local function neFonts(r: Bytes.Reader, ne: number): ({ { number } }?, string?) return out, nil end --- the RT_FONT (8) resources of a PE executable: { { offset, length } } +-- RT_FONT: resource type 8 local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) local h = r:sub(pe + 4, 20) h:skip(2) @@ -190,7 +184,6 @@ local function peFonts(r: Bytes.Reader, pe: number): ({ { number } }?, string?) if opt.err or rsrcRva == 0 then return {}, nil end - -- the section holding the resources local secs = r:sub(pe + 24 + optSize, nsec * 40) local base, rva0 = -1, 0 for _ = 1, nsec do diff --git a/src/Rosetta/font/hershey/init.luau b/src/Rosetta/font/hershey/init.luau index 3ca26d9..275a81f 100644 --- a/src/Rosetta/font/hershey/init.luau +++ b/src/Rosetta/font/hershey/init.luau @@ -1,13 +1,7 @@ --!strict --- font/hershey: Hershey vector fonts in the JHF text layout (James Hurt's distribution of the Hershey glyphs: per glyph --- a 5-column id, a 3-column vertex count, the left / right extents and the vertices as character pairs offset by "R", --- " R" lifting the pen; records continue over 72-column lines) as the standard Font: outlines are open stroke paths --- (moveTo / lineTo, no close; meta.strokes = true), rasterize strokes them through codecs/image/Raster --- (opts.strokeWidth, default 2 units). Units are Hershey units (unitsPerEm 32, y up, baseline at the Hershey y = 9 of --- the Roman fonts: ascent 21, descent 7 for capitals / descenders). Code points: opts.map = "ascii" (default: glyph i --- of the file is code point 32 + i, as the romans / futural / ... .jhf files are laid out) or "id" (the Hershey glyph --- number is the code point). Written from the JHF layout notes of the Hershey font distribution. Not supported: --- writing, the Hershey "occidental" index files (.hmp), filled rendering. +-- font/hershey: Hershey vector fonts, JHF layout (5-column id, 3-column vertex count, extents, vertices as character +-- pairs offset by "R", " R" lifts the pen; records continue over 72-column lines). Units: unitsPerEm 32, y up. +-- Not supported: writing, .hmp index files, filled rendering. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -26,8 +20,8 @@ local Hershey = { } export type DecodeOptions = { - map: ("ascii" | "id")?, -- how glyphs map to code points (default "ascii") - strokeWidth: number?, -- stroke width in font units for rasterize (default 2) + map: ("ascii" | "id")?, -- default "ascii" + strokeWidth: number?, -- font units; default 2 maxGlyphs: number?, -- default 65536 } @@ -93,7 +87,6 @@ function Face.outline(self: any, g: number): { any }? return out end --- rasterize(g, px) -> alpha8 Image of the stroked glyph (img.meta.left / top / advance in pixels) function Face.rasterize(self: any, g: number, px: number): Types.Image? local gl = self._glyphs[g + 1] if not gl or type(px) ~= "number" or not (px > 0) or px > 4096 then diff --git a/src/Rosetta/font/pcf/init.luau b/src/Rosetta/font/pcf/init.luau index f34e7c1..c309ea3 100644 --- a/src/Rosetta/font/pcf/init.luau +++ b/src/Rosetta/font/pcf/init.luau @@ -1,11 +1,6 @@ --!strict --- font/pcf: X11 Portable Compiled Format bitmap fonts (.pcf; .pcf.gz loads through the api's gzip unwrap) as the --- standard Font with a bitmap strike (codecs/font/Bitmap): the table of contents, PROPERTIES (meta.properties), --- ACCELERATORS / BDF_ACCELERATORS (font ascent / descent), METRICS (compressed and not), BITMAPS in any glyph pad --- (1 / 2 / 4 / 8), scan unit and bit / byte order, BDF_ENCODINGS (one- and two-byte), SWIDTHS and GLYPH_NAMES. --- Code points as font/bdf: the encoding is Unicode for ISO10646, ISO8859-1 and registry-less fonts; other charsets --- keep glyphs unmapped (meta.encodings). Written from the PCF description in libXfont / FreeType's pcf driver --- documentation (no code copied). Not supported: writing (write BDF and compile it with bdftopcf), INK_METRICS. +-- font/pcf: X11 Portable Compiled Format bitmap fonts, from the PCF description in libXfont / FreeType's pcf driver +-- docs (no code copied); code points as font/bdf. Not supported: writing, INK_METRICS. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -38,7 +33,6 @@ end -- ------------------------------------------------------------------------------------------------ decode type Table = { format: number, size: number, offset: number } --- a reader positioned after a table's format word, with the integer readers for its byte order type TR = { r: Bytes.Reader, format: number, big: boolean } local function open(r: Bytes.Reader, t: Table?): TR? @@ -91,7 +85,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if r.err then return nil, r.err end - -- properties local props: { [string]: any } = {} local pt = open(r, tables[PROPERTIES]) if pt then @@ -122,14 +115,12 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) return nil, Err.new(Err.TRUNCATED, "properties table") end end - -- accelerators: ascent / descent local ascent: number?, descent: number? = nil, nil local at = open(r, tables[BDF_ACCELERATORS] or tables[ACCELERATORS]) if at then at.r:skip(8) ascent, descent = i32(at), i32(at) end - -- metrics local mt = open(r, tables[METRICS]) if not mt then return nil, Err.new(Err.CORRUPT, "no METRICS table") @@ -152,7 +143,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) if mt.r.err then return nil, Err.new(Err.TRUNCATED, "metrics table") end - -- bitmaps local bt = open(r, tables[BITMAPS]) if not bt then return nil, Err.new(Err.CORRUPT, "no BITMAPS table") @@ -202,7 +192,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local px = Bitmap.unpack(bits, offsets[k], w, h, stride) glyphs[k] = { width = w, height = h, left = m[1], top = m[4], advance = m[3], pixels = px } end - -- encodings local encodings: { [number]: number } = {} local default: number? = nil local et = open(r, tables[BDF_ENCODINGS]) @@ -233,7 +222,6 @@ function Pcf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end end end - -- glyph names local nt = open(r, tables[GLYPH_NAMES]) if nt then local n = u32(nt) diff --git a/src/Rosetta/font/psf/init.luau b/src/Rosetta/font/psf/init.luau index 0fcd14f..1b71bd2 100644 --- a/src/Rosetta/font/psf/init.luau +++ b/src/Rosetta/font/psf/init.luau @@ -1,14 +1,7 @@ --!strict --- font/psf: Linux console fonts, PC Screen Font versions 1 (magic 36 04: 8 pixels wide, 256 or 512 glyphs, UCS-2 --- Unicode table with FFFF / FFFE) and 2 (magic 72 B5 4A 86: any width, UTF-8 Unicode table with FF / FE), read and --- written, as the standard Font with a bitmap strike (codecs/font/Bitmap). Every code point of a glyph's table entry --- maps to it (strike.map; combining sequences after FE / FFFE are kept in meta.sequences); fonts without a table map --- glyph i to code point i (meta.unicode = false). Console cells have no baseline: the strike's ascent is the cell --- height (descent 0) and every glyph fills its cell. .psf.gz / .psfu.gz load through the api's gzip unwrap. Writing: --- PSF 2 by default (opts.version = 1 for PSF 1: 8-pixel cells, 256 or 512 glyphs) from any Font through --- Bitmap.strike, glyphs placed in a cell of the strike's widest advance and ascent + descent; a PSF read before keeps --- its Unicode table (meta.unicodeTable) and its table / no-table choice. Written from the kbd --- project's psf documentation (Andries Brouwer). +-- font/psf: Linux console fonts (kbd project's psf docs, Andries Brouwer): PSF 1 (magic 36 04, UCS-2 table, FFFF / +-- FFFE) and PSF 2 (magic 72 B5 4A 86, UTF-8 table, FF / FE), read and written (PSF 2 by default); the ascent is the +-- cell height. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -28,10 +21,10 @@ local Psf = { export type DecodeOptions = { maxGlyphs: number? } -- default 65536 export type EncodeOptions = { - version: number?, -- 1 or 2 (default 2) - px: number?, -- pixel size for outline fonts (default 16) - chars: (string | { number })?, -- code points for outline fonts (default printable ASCII) - unicode: boolean?, -- write the Unicode table (default true) + version: number?, -- 1 or 2; default 2 + px: number?, -- default 16 + chars: (string | { number })?, -- default printable ASCII + unicode: boolean?, -- default true } -- ------------------------------------------------------------------------------------------------ sniff @@ -103,7 +96,7 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end local map: { [number]: number } = {} local sequences = {} - local unicodeTable: { { any } } = {} -- per glyph: code points and { sequence } tables, in file order + local unicodeTable: { { any } } = {} if hasTable then local t = r:sub(glyphAt + count * size) for i = 0, count - 1 do @@ -141,7 +134,6 @@ function Psf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) inSeq = true continue end - -- UTF-8 local n = if b < 0x80 then 0 elseif b >= 0xF0 then 3 elseif b >= 0xE0 then 2 elseif b >= 0xC0 then 1 else -1 if n < 0 then return nil, Err.new(Err.CORRUPT, "bad UTF-8 in the Unicode table") @@ -208,7 +200,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) if n == 0 then return nil, Err.new(Err.ARG, "no glyphs") end - -- the cell local width = 0 for _, g in glyphs do width = math.max(width, g.advance, g.left + g.width) @@ -241,7 +232,6 @@ function Psf.encode(font: any, opts: EncodeOptions?): (buffer?, Err.Err?) end buffer.copy(cells, (i - 1) * size, Bitmap.pack(cell, width, height, stride)) end - -- the Unicode table: each glyph's code point and the extra mappings onto it local cps: { { number } } = {} for i = 1, count do cps[i] = {} diff --git a/src/Rosetta/font/ttf/init.luau b/src/Rosetta/font/ttf/init.luau index c65b2bd..b671265 100644 --- a/src/Rosetta/font/ttf/init.luau +++ b/src/Rosetta/font/ttf/init.luau @@ -1,9 +1,7 @@ --!strict --- font/ttf: TrueType and OpenType fonts (.ttf, .otf with CFF outlines) and collections (.ttc / .otc), read into the --- standard Font (Types.Font) by codecs/font/TrueType: metrics, names, cmap, outlines (glyf or CFF), kerning ('kern' table, --- GPOS pair kerning) and rasterize(glyph, px) through codecs/image/Raster. Ported from stb_truetype 1.26 (public domain / --- MIT) via imgui-luau's imstb_truetype.lua; see codecs/font/TrueType. opts.index picks the font of a collection. --- Not supported: hinting, variable fonts, bitmap / colour glyphs, GSUB, writing. +-- font/ttf: TrueType / OpenType (glyf or CFF) fonts and collections via codecs/font/TrueType, ported from stb_truetype +-- 1.26 (public domain / MIT) via imgui-luau's imstb_truetype.lua. Not supported: hinting, variable fonts, bitmap / +-- colour glyphs, GSUB, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -21,7 +19,7 @@ local Ttf = { } export type DecodeOptions = { - index: number?, -- the font of a collection (default 0) + index: number?, -- default 0 } -- ------------------------------------------------------------------------------------------------ sniff @@ -44,7 +42,6 @@ function Ttf.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ extras --- count(r) -> the number of fonts in the file (1 unless a collection) function Ttf.count(r: Bytes.Reader): number return TrueType.count(r.buf, r.base) end diff --git a/src/Rosetta/font/type1/Charstring.luau b/src/Rosetta/font/type1/Charstring.luau index e1b4f4a..036542b 100644 --- a/src/Rosetta/font/type1/Charstring.luau +++ b/src/Rosetta/font/type1/Charstring.luau @@ -1,15 +1,8 @@ --!strict --- font/type1/Charstring: the Type 1 charstring interpreter (Adobe Type 1 Font Format, chapter 6 and 8): decrypted --- charstrings to path commands (moveTo / lineTo / cubicTo / close, font units, y up) plus the advance and side --- bearing. hsbw / sbw, the r/h/v moveto, lineto and curveto operators, closepath, callsubr / return, div, --- callothersubr / pop with the standard OtherSubrs (0..2: flex, emitted as its two curves; 3: hint replacement; --- others pass their arguments back), setcurrentpoint, seac (the base and accent glyphs from StandardEncoding codes, --- through a callback), endchar; hints (hstem / vstem / hstem3 / vstem3 / dotsection) are ignored. New code from the --- specification. Never throws: malformed charstrings return nil, message (an operation budget stops subroutine loops). +-- font/type1/Charstring: Type 1 charstring interpreter (Adobe Type 1 Font Format, chapters 6 and 8); hints ignored. local Charstring = {} export type Result = { cmds: { any }, advance: number, sbx: number } --- fonts: subrs (decrypted subroutines), lenIV handled by the caller; seac(code) -> the base / accent Result export type Context = { subrs: { buffer }, seac: ((code: number) -> Result?)? } local readu8 = buffer.readu8 @@ -18,7 +11,7 @@ function Charstring.run(cs: buffer, ctx: Context): (Result?, string?) local cmds: { any } = {} local stack: { number } = {} local sp = 0 - local ps: { number } = {} -- the PostScript stack callothersubr / pop use + local ps: { number } = {} local x, y = 0, 0 local advance, sbx = 0, 0 local open = false diff --git a/src/Rosetta/font/type1/init.luau b/src/Rosetta/font/type1/init.luau index bbca329..1024e34 100644 --- a/src/Rosetta/font/type1/init.luau +++ b/src/Rosetta/font/type1/init.luau @@ -1,12 +1,7 @@ --!strict --- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA (hex eexec section), as the --- standard Font: the cleartext dictionary (FontName, FamilyName, FullName, Weight, ItalicAngle, FontMatrix, FontBBox, --- Encoding: StandardEncoding or the font's own array), eexec decryption (r = 55665), the Private dictionary (lenIV, --- Subrs, CharStrings with RD / -| binary strings, charstring decryption r = 4330) and the Type 1 charstring --- interpreter (font/type1/Charstring: flex, hint replacement, seac) to outlines; code points from the encoding's glyph --- names through codecs/font/GlyphNames (AGLFN, uniXXXX), plus every other glyph name the AGL knows; rasterize through --- codecs/image/Raster. Written from Adobe's "Adobe Type 1 Font Format" (1990). Not supported: hinting, Multiple --- Master and CID-keyed (Type 9 / 11) fonts, writing. +-- font/type1: PostScript Type 1 fonts, PFB (segments 80 01 / 80 02 / 80 03) and PFA, from Adobe's "Adobe Type 1 Font +-- Format" (1990): eexec (r = 55665) and charstring (r = 4330) decryption, code points via codecs/font/GlyphNames. +-- Not supported: hinting, Multiple Master and CID-keyed (Type 9 / 11) fonts, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -41,7 +36,6 @@ function Type1.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- the cleartext and the (still encrypted) binary eexec section of a PFB or PFA local function sections(r: Bytes.Reader): (string?, buffer?, string?) local b = r.buf local n = r:size() @@ -204,7 +198,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) local priv = decrypt(enc, 0, buffer.len(enc), 55665, 4) local ptext = buffer.tostring(priv) local lenIV = tonumber(string.match(ptext, "/lenIV%s+(%-?%d+)") or "4") or 4 - -- Subrs local subrs: { buffer } = {} local function charstring(p: number, len: number): buffer? local raw = binaryAt(priv, p, len) @@ -241,7 +234,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) p = e + n end end - -- CharStrings local names: { string } = {} local charstrings: { buffer } = {} local byName: { [string]: number } = {} @@ -252,7 +244,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) break end local e = e0 :: number - -- stop at the end of the dictionary if string.find(string.sub(ptext, p, s), "%send%s") then break end @@ -281,7 +272,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) charstrings[1], charstrings[nd + 1] = charstrings[nd + 1], charstrings[1] byName[names[1]], byName[names[nd + 1]] = 0, nd end - -- the encoding local encoding: { [number]: string } = {} if string.find(clear, "/Encoding%s+StandardEncoding") then for code, gname in GlyphNames.STANDARD do @@ -306,7 +296,6 @@ function Type1.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?) cmap[cp] = k - 1 end end - -- font matrix / bbox local fm = string.match(clear, "/FontMatrix%s*[%[{]([^%]}]*)[%]}]") local scale = 0.001 if fm then diff --git a/src/Rosetta/font/woff/init.luau b/src/Rosetta/font/woff/init.luau index c992b4c..d33dfce 100644 --- a/src/Rosetta/font/woff/init.luau +++ b/src/Rosetta/font/woff/init.luau @@ -1,7 +1,6 @@ --!strict --- font/woff: WOFF 1.0 (W3C Recommendation, 2012): an sfnt font whose tables are zlib-compressed one by one. Decoding --- rebuilds the sfnt and reads it through codecs/font/TrueType (TrueType or CFF outlines, see font/ttf); the extended --- metadata XML is kept in meta.woffMetadata. Written from the spec. Not supported: writing. +-- font/woff: WOFF 1.0 (W3C Recommendation, 2012): zlib-compressed sfnt tables, rebuilt and read through +-- codecs/font/TrueType; the metadata XML goes to meta.woffMetadata. Not supported: writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,7 +19,7 @@ local Woff = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ sniff @@ -29,7 +28,6 @@ function Woff.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file (a buffer) | nil, Err function Woff.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?, string?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local base = r.base diff --git a/src/Rosetta/font/woff2/Rebuild.luau b/src/Rosetta/font/woff2/Rebuild.luau index b156e55..5d2199f 100644 --- a/src/Rosetta/font/woff2/Rebuild.luau +++ b/src/Rosetta/font/woff2/Rebuild.luau @@ -1,10 +1,5 @@ --!strict --- font/woff2/Rebuild: rebuilds the sfnt of a WOFF2 file (W3C WOFF2 Recommendation, 2024 edition): the table --- directory, the Brotli stream, the transformed glyf / loca tables (section 5: nContour, nPoints, flag, glyph, --- composite, bbox and instruction streams, triplet-encoded coordinates, the overlap bitmap) and the transformed hmtx --- (section 6: side bearings from the glyph bounds). Written from the spec. Not supported: collections (ttcf flavor). --- --- Never throws: malformed data returns nil, message. +-- font/woff2/Rebuild: the sfnt of a WOFF2 file (W3C WOFF2, 2024 edition: section 5 glyf / loca, section 6 hmtx). local Bytes = require("@rosetta/core/Bytes") local Brotli = require("@rosetta/codecs/compress/Brotli") @@ -40,7 +35,6 @@ local function base128(r: Bytes.Reader): number? return nil end --- a cursor over a stream inside the decompressed block type Stream = { buf: buffer, p: number, e: number, bad: boolean } local function stream(b: buffer, p: number, n: number): Stream return { buf = b, p = p, e = p + n, bad = false } @@ -77,7 +71,6 @@ local function withSign(flag: number, v: number): number return if band(flag, 1) ~= 0 then v else -v end --- the glyf transform -> glyf bytes (a Writer), loca offsets, per-glyph xMin (for hmtx), numGlyphs, indexFormat local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, string?) local h = stream(b, p, n) su16(h) -- reserved @@ -132,7 +125,6 @@ local function glyf(b: buffer, p: number, n: number, maxBytes: number): (any?, s return nil, "empty glyph with a bounding box" end elseif nc > 0 then - -- simple glyph local ends = table.create(nc, 0) local total = 0 for c = 1, nc do @@ -363,7 +355,6 @@ local function hmtx(b: buffer, p: number, n: number, numGlyphs: number, numH: nu return out:finish(), nil end --- sfnt(r, maxBytes) -> sfnt buffer | nil, message, code ("truncated" / "corrupt" / "unsupported" / "limit") function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, string?) if not r:match("wOF2") then return nil, "bad signature", "corrupt" @@ -433,7 +424,6 @@ function Rebuild.sfnt(r: Bytes.Reader, maxBytes: number): (buffer?, string?, str if buffer.len(data) < streamTotal then return nil, "decompressed stream shorter than the tables", "corrupt" end - -- the tables, glyf / loca / hmtx rebuilt local byTag: { [string]: any } = {} for _, e in dir do byTag[e.tag] = e diff --git a/src/Rosetta/font/woff2/init.luau b/src/Rosetta/font/woff2/init.luau index b696609..c7d2018 100644 --- a/src/Rosetta/font/woff2/init.luau +++ b/src/Rosetta/font/woff2/init.luau @@ -1,7 +1,6 @@ --!strict --- font/woff2: WOFF 2.0 (W3C Recommendation): sfnt tables in one Brotli stream, with the glyf / loca and hmtx --- transforms. Decoding rebuilds the sfnt (font/woff2/Rebuild) and reads it through codecs/font/TrueType (TrueType or CFF --- outlines, see font/ttf). Written from the spec; Brotli is codecs/compress/Brotli. Not supported: collections, writing. +-- font/woff2: WOFF 2.0 (W3C Recommendation): Brotli-compressed sfnt tables with the glyf / loca and hmtx transforms, +-- rebuilt by font/woff2/Rebuild. Not supported: collections, writing. -- ------------------------------------------------------------------------------------------------ requires local Err = require("@rosetta/core/Err") @@ -20,7 +19,7 @@ local Woff2 = { } export type DecodeOptions = { - maxBytes: number?, -- refuse a font whose sfnt is bigger (default 2^28) + maxBytes: number?, -- default 2^28 } -- ------------------------------------------------------------------------------------------------ constants @@ -30,7 +29,6 @@ function Woff2.sniff(r: Bytes.Reader): number end -- ------------------------------------------------------------------------------------------------ decode --- sfnt(r, opts?) -> the rebuilt sfnt font file | nil, Err function Woff2.sfnt(r: Bytes.Reader, opts: DecodeOptions?): (buffer?, Err.Err?) local maxBytes = (opts and opts.maxBytes) or 2 ^ 28 local at = r.base diff --git a/src/Rosetta/vector/svg/Parse.luau b/src/Rosetta/vector/svg/Parse.luau index a20655c..5189da4 100644 --- a/src/Rosetta/vector/svg/Parse.luau +++ b/src/Rosetta/vector/svg/Parse.luau @@ -1,11 +1,5 @@ --!strict --- vector/svg/Parse: an SVG document (a codecs/text/Xml tree) to a Types.Vector: the cascade (presentation attributes, ---