codecs/text: comments to specs only

This commit is contained in:
4DBug committed 2026-11-01 01:59:16 -05:00
1 parent f626fb4295
commit 492d6662df
12 files changed
+97 -294

No files matched your search

+10 -23
View File
@@ -1,9 +1,7 @@
--!strict
--!native
-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json. Iterative (an explicit container stack, so deep nesting
-- is a LIMIT error, never a stack overflow), strict grammar (no comments, trailing commas, leading zeros, NaN, single
-- quotes or raw control characters), \u escapes with surrogate pairs (lone surrogates become WTF-8 bytes). Also the
-- pull tokenizer behind Json.events. Never throws: failures return nil, message, offset (0-based byte offset).
-- codecs/text/Json/Decode: the RFC 8259 parser behind codecs/text/Json: iterative, strict grammar.
-- \u escapes with surrogate pairs; lone surrogates become WTF-8 bytes.
local Text = require("@rosetta/codecs/text/Text")
local Types = require("@rosetta/Types")
@@ -14,10 +12,10 @@ local tonumber = tonumber
local concat = table.concat
export type Options = {
ordered: boolean?, -- every object is a Types.object with its key order (default false: only empty objects are)
bigInts: ("number" | "string")?, -- integers beyond +-2^53: "string" keeps their exact text (default "number")
null: any?, -- the value for null (default Types.null)
maxDepth: number?, -- nesting limit (default 1000)
ordered: boolean?,
bigInts: ("number" | "string")?,
null: any?,
maxDepth: number?,
}
local ESC: { [number]: string } = {
@@ -31,7 +29,6 @@ local ESC: { [number]: string } = {
[116] = "\t",
}
-- utf8 bytes of a code point (surrogates too: WTF-8)
local utf8char = Text.utf8char
Decode.utf8char = utf8char
@@ -43,7 +40,6 @@ local function hex4(s: string, i: number): number?
return tonumber(h, 16)
end
-- string(s, i) -> value, next | nil, message, offset. i is at the opening quote.
local function str(s: string, i: number): (string?, any, number?)
local j = find(s, '[%z\1-\31"\\]', i + 1)
if not j then
@@ -102,7 +98,6 @@ local function str(s: string, i: number): (string?, any, number?)
end
Decode.string = str
-- number(s, i) -> value, next | nil, message, offset
local function num(s: string, i: number, bigStrings: boolean): (any, any, number?)
local p = i
if byte(s, p) == 45 then
@@ -153,8 +148,6 @@ local function num(s: string, i: number, bigStrings: boolean): (any, any, number
end
Decode.number = num
-- decode(s, i, opts) -> value, next | nil, message, offset. Parses one value starting at i (leading whitespace
-- skipped); next is the position after the value (trailing whitespace not skipped).
function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
local o: Options = opts or {}
local ordered = o.ordered == true
@@ -163,9 +156,9 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
local maxDepth = o.maxDepth or 1000
local object = Types.object
local stackT: { any } = {} -- containers
local stackK: { any } = {} -- object: the pending key; array: the count
local stackO: { any } = {} -- object: its key order (or true); array: false
local stackT: { any } = {}
local stackK: { any } = {}
local stackO: { any } = {}
local depth = 0
local n = #s
local value: any
@@ -246,7 +239,6 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
end
value, i = v, ni
end
-- attach the value to the open containers, closing them as their ends come
while haveValue do
if depth == 0 then
return value, i
@@ -303,17 +295,13 @@ function Decode.value(s: string, i: number, opts: Options?): (any, any, number?)
end
end
-- events: a pull tokenizer. next() -> event, value | nil at the end | "error", message, offset. Events: "object",
-- "endObject", "array", "endArray", "key" (string), "value" (scalar). The grammar is checked as it goes.
function Decode.events(s: string, i: number, opts: Options?): () -> (string?, any, number?)
local o: Options = opts or {}
local bigStrings = o.bigInts == "string"
local nullv = if o.null ~= nil then o.null else Types.null
local maxDepth = o.maxDepth or 1000
local stack: { boolean } = {} -- true = object
local stack: { boolean } = {}
local depth = 0
-- state: "value" (a value expected), "first" (after { or [: value / key or close), "after" (after a value),
-- "key" (a key expected), "done", "dead"
local state = "value"
local n = #s
local function fail(msg: string, at: number): (string, any, number)
@@ -378,7 +366,6 @@ function Decode.events(s: string, i: number, opts: Options?): () -> (string?, an
state = "value"
return "key", k
end
-- a value
local after = if depth == 0 then "done" else "after"
if c == 123 or c == 91 then
depth += 1
+9 -16
View File
@@ -1,9 +1,6 @@
--!strict
--!native
-- codecs/text/Json/Encode: the serializer behind codecs/text/Json. Compact or pretty (indent), objects in their Types.object key
-- order (plain tables: sorted keys), arrays for tables with keys 1..n, shortest round-trip number text, optional
-- ASCII-only output. Never throws: bad values (cycles, NaN / inf, functions, non-string keys that are not numbers)
-- return nil, message.
-- codecs/text/Json/Encode: the RFC 8259 serializer behind codecs/text/Json.
local Types = require("@rosetta/Types")
local Encode = {}
@@ -13,13 +10,13 @@ local floor, huge = math.floor, math.huge
local concat = table.concat
export type Options = {
indent: (number | string)?, -- pretty print: spaces per level (or the indent string); default compact
sortKeys: boolean?, -- plain tables' keys sorted (default true; false = next() order, faster)
ascii: boolean?, -- escape every non-ASCII character as \uXXXX (default false: UTF-8 as is)
nan: ("error" | "null")?, -- NaN / inf: an error (default) or null
emptyTable: ("array" | "object")?, -- what a plain empty table is (default "array"; Types.object() is "{}")
maxDepth: number?, -- nesting limit (default 1000; also catches cycles)
escapeSlash: boolean?, -- write / as \/ (default false)
indent: (number | string)?,
sortKeys: boolean?,
ascii: boolean?,
nan: ("error" | "null")?,
emptyTable: ("array" | "object")?,
maxDepth: number?,
escapeSlash: boolean?,
}
local ESCAPES: { [string]: string } = {
@@ -47,7 +44,6 @@ local function utf16(cp: number): string
return format("\\u%04x\\u%04x", 0xD800 + cp // 1024, 0xDC00 + cp % 1024)
end
-- asciify a UTF-8 string's non-ASCII sequences (invalid bytes become \u00XX of the byte: lossy but never throws)
local function asciiSeq(seq: string): string
local out = {}
local i, n = 1, #seq
@@ -69,7 +65,7 @@ local function asciiSeq(seq: string): string
return concat(out)
end
-- string(s, ascii, slash) -> the quoted JSON string (ascii: DEL too, like Python's ensure_ascii)
-- ascii escapes DEL too, like Python's ensure_ascii
local function quote(s: string, ascii: boolean?, slash: boolean?): string
local pat = if slash then '[%z\1-\31"\\/]' else '[%z\1-\31"\\]'
if string.find(s, pat) then
@@ -85,7 +81,6 @@ end
Encode.quote = quote
local FLOAT_FORMATS = { "%.15g", "%.16g", "%.17g" }
-- number(x) -> the shortest text that reads back as x | nil for NaN / inf
local function number(x: number): string?
if x ~= x or x == huge or x == -huge then
return nil
@@ -114,7 +109,6 @@ local function keyLess(a: any, b: any): boolean
return a < b
end
-- kind(t, emptyObject) -> "array" (keys exactly 1..n) | "object"
local function kind(t: { [any]: any }, emptyObject: boolean): string
if Types.isObject(t) then
return "object"
@@ -295,7 +289,6 @@ end
Encode.state = state
Encode.write = value
-- encode(v, opts) -> text | nil, message
function Encode.encode(v: any, opts: Options?, nullv: any?): (string?, string?)
local st = state(opts, nullv)
if not value(st, v, 0) then
+4 -31
View File
@@ -1,18 +1,5 @@
--!strict
-- codecs/text/Json: JSON (RFC 8259 / ECMA-404) parse and serialize, the engine data/json, glTF, TMJ, ... use. New code.
-- Values are plain Luau: objects -> tables (string keys), arrays -> arrays, null -> Types.null (opts.null), numbers
-- -> doubles (opts.bigInts = "string" keeps integers past 2^53 as their text). Empty objects are Types.object() so
-- they write back as {}; opts.ordered makes every object a Types.object with its key order.
--
-- local Json = require("@rosetta/codecs/text/Json")
-- local v, err = Json.decode('{"a": [1, 2, null]}') -- string | buffer; nil, Err on bad input
-- local s = Json.encode(v, { indent = 2 }) -- string | nil, Err
-- for ev, x in Json.events(text) do ... end -- pull events without building the tree
-- for i, v, err in Json.lines(ndjson) do ... end -- JSON Lines / concatenated JSON values
-- local w = Json.writer({ indent = 2 }); w:beginObject(); w:key("a"); w:value(1); w:endObject(); w:tostring()
--
-- Streaming: decodeAt(src, pos) parses one value and returns where the next begins; events() is a pull tokenizer;
-- writer() builds output incrementally and flush() hands back the text so far. Never throws.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Decode = require("@rosetta/codecs/text/Json/Decode")
@@ -46,8 +33,6 @@ local function fail(msg: any, at: any, n: number): Err.Err
return Err.new(code, m, at)
end
-- decode(src, opts?) -> value | nil, Err. One JSON text: a value with optional whitespace around it (a UTF-8 BOM is
-- skipped). Note a JSON null top-level value decodes to opts.null (Types.null by default), never nil.
function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?)
local s, terr = text(src)
if not s then
@@ -65,8 +50,6 @@ function Json.decode(src: string | buffer, opts: DecodeOptions?): (any, Err.Err?
return v, nil
end
-- decodeAt(src, pos?, opts?) -> value, nextPos | nil, Err. One value starting at pos (1-based, default 1; leading
-- whitespace skipped); nextPos is just past it. nil, nil when only whitespace is left.
function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?): (any, any)
local s, terr = text(src)
if not s then
@@ -83,8 +66,6 @@ function Json.decodeAt(src: string | buffer, pos: number?, opts: DecodeOptions?)
return v, ni
end
-- lines(src, opts?) -> iterator: index, value (JSON Lines, or any whitespace-separated sequence of JSON values). A
-- bad value gives a last index, nil, Err: for i, v, err in Json.lines(s) do if err then ... end end
function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?, any, Err.Err?)
local s, terr = text(src)
local pos = 1
@@ -112,8 +93,6 @@ function Json.lines(src: string | buffer, opts: DecodeOptions?): () -> (number?,
end
end
-- events(src, opts?) -> iterator: event, value. Events: "object", "endObject", "array", "endArray", "key" (the key),
-- "value" (a scalar), and on bad input one final "error", Err.
function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?, any)
local s, terr = text(src)
if not s then
@@ -138,7 +117,6 @@ function Json.events(src: string | buffer, opts: DecodeOptions?): () -> (string?
end
end
-- encode(value, opts?) -> string | nil, Err
function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
local s, msg = Encode.encode(value, opts)
if not s then
@@ -147,13 +125,9 @@ function Json.encode(value: any, opts: EncodeOptions?): (string?, Err.Err?)
return s, nil
end
Json.quote = Encode.quote -- quote(s) -> '"..."' with JSON escapes
Json.number = Encode.number -- number(x) -> the shortest round-trip text (nil for NaN / inf)
Json.quote = Encode.quote
Json.number = Encode.number
-- ------------------------------------------------------------------------------------------------ writer
-- writer(opts?) -> a streaming Writer: beginObject / endObject / beginArray / endArray / key(k) / value(v) (any
-- value, encoded whole), then tostring() for everything or flush() for the text since the last flush. Misuse (a key
-- outside an object, a value where a key is due, unbalanced ends) is recorded in w.err and later calls do nothing.
export type Writer = {
err: Err.Err?,
beginObject: (self: Writer) -> Writer,
@@ -169,10 +143,10 @@ export type Writer = {
function Json.writer(opts: EncodeOptions?): Writer
local st = Encode.state(opts)
local ind = st.indent
local kinds: { boolean } = {} -- true = object
local kinds: { boolean } = {}
local counts: { number } = {}
local depth = 0
local keyDone = false -- an object's key written, its value due
local keyDone = false
local flushed: { string } = {}
local w: any = { err = nil }
local function bad(msg: string)
@@ -180,7 +154,6 @@ function Json.writer(opts: EncodeOptions?): Writer
w.err = Err.new(Err.ARG, msg)
end
end
-- before an element: a comma / newline as needed; false when the position is wrong
local function slot(isKey: boolean): boolean
if w.err then
return false