json.bend source
json.bend on the hub · documented module
# JSON (RFC 8259) from bytes, in one pass: a lexer state machine whose finished tokens drive a parser stack, so the# text never becomes a token list. Strings are decoded to code points (escapes, surrogate pairs, UTF-8); a number is# kept as an unsigned 32-bit integer when it is one, else marked as not one. Commas and colons are separators: the# parser checks that containers nest and close, and that object keys are strings, not every comma.import Baseimport ./utf8.bend as Utype J is Data: JNull{} JBool{b: Bool} JNum{v: U32, int: Bool} JStr{s: List<&2, U32>} JArr{xs: List<&2, J>} JObj{kvs: List<&2, KV>}type KV is Data: KV{k: List<&2, U32>, v: J}# ---- the parser: a stack of open containers ----type Fr is Data: FArr{xs: List<&2, J>} FObj{kvs: List<&2, KV>, key: Maybe<&2, List<&2, U32>>}# stack: open containers, innermost first; top: the finished top-level value; bad: the first errortype Ps is Data: Ps{stack: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>}def p_bad(why: String, p: Ps) -> Ps: match p: case Ps{stack, top, bad}: Ps{stack, top, Maybe.or(&2, String, bad, Some{why})}def key_of(v: J) -> Maybe<&2, List<&2, U32>>: match v: case JStr{s}: Some{s} case JNull{}: None{} case JBool{b}: None{} case JNum{n, i}: None{} case JArr{xs}: None{} case JObj{kvs}: None{}def obj_key(k: Maybe<&2, List<&2, U32>>, kvs: List<&2, KV>, rest: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match k: case Some{s}: Ps{FObj{kvs, Some{s}} <> rest, top, bad} case None{}: Ps{FObj{kvs, None{}} <> rest, top, Maybe.or(&2, String, bad, Some{"an object key that is not a string"})}def obj_value(key: Maybe<&2, List<&2, U32>>, v: J, kvs: List<&2, KV>, rest: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match key: case Some{k}: Ps{FObj{KV{k, v} <> kvs, None{}} <> rest, top, bad} case None{}: obj_key(key_of(v), kvs, rest, top, bad)def add_frame(f: Fr, v: J, rest: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match f: case FArr{xs}: Ps{FArr{v <> xs} <> rest, top, bad} case FObj{kvs, key}: obj_value(key, v, kvs, rest, top, bad)def add_top(top: Maybe<&2, J>, v: J, bad: Maybe<&2, String>) -> Ps: match top: case None{}: Ps{[], Some{v}, bad} case Some{t}: Ps{[], Some{t}, Maybe.or(&2, String, bad, Some{"more than one value"})}# a finished value goes into the innermost open container, or becomes the top-level valuedef add_in(stack: List<&2, Fr>, v: J, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match stack: case []: add_top(top, v, bad) case f <> rest: add_frame(f, v, rest, top, bad)def add(p: Ps, v: J) -> Ps: match p: case Ps{stack, top, bad}: add_in(stack, v, top, bad)def open(p: Ps, f: Fr) -> Ps: match p: case Ps{stack, top, bad}: Ps{f <> stack, top, bad}def close_obj(key: Maybe<&2, List<&2, U32>>, kvs: List<&2, KV>, rest: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match key: case None{}: add(Ps{rest, top, bad}, JObj{List.reverse(&2, KV, kvs)}) case Some{k}: Ps{rest, top, Maybe.or(&2, String, bad, Some{"a key without a value closing an object"})}def close_frame(f: Fr, arr: Bool, rest: List<&2, Fr>, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match f arr: case FArr{xs} True{}: add(Ps{rest, top, bad}, JArr{List.reverse(&2, J, xs)}) case FObj{kvs, key} False{}: close_obj(key, kvs, rest, top, bad) case FArr{xs} False{}: Ps{rest, top, Maybe.or(&2, String, bad, Some{"a } closing an array"})} case FObj{kvs, key} True{}: Ps{rest, top, Maybe.or(&2, String, bad, Some{"a ] closing an object"})}def close_in(stack: List<&2, Fr>, arr: Bool, top: Maybe<&2, J>, bad: Maybe<&2, String>) -> Ps: match stack: case []: Ps{[], top, Maybe.or(&2, String, bad, Some{"a closing bracket with nothing open"})} case f <> rest: close_frame(f, arr, rest, top, bad)# ---- the lexer: bytes to events, which the parser folds (parse), or chunks lexed in parallel (parse_par) ----type Ev is Data: EOpenA{} EOpenO{} ECloseA{} ECloseO{} EVal{v: J} EBad{why: String}def close(p: Ps, arr: Bool) -> Ps: match p: case Ps{stack, top, bad}: close_in(stack, arr, top, bad)type Lx is Data: XTop{} XStr{bs: List<&2, U32>} XEsc{bs: List<&2, U32>} # \u: hex digits left, the value so far, and a high surrogate waiting for its low half (0: none) XHex{bs: List<&2, U32>, left: U32, v: U32, hi: U32} XLow{bs: List<&2, U32>, hi: U32} XLowU{bs: List<&2, U32>, hi: U32} XNum{v: U32, int: Bool} XLit{rest: List<&2, U32>, val: J}type St is Data: St{lx: Lx, p: List<&2, Ev>}def is_digit(+b: U32) -> Bool: Bool.and(U32.is_ge(b, 48), U32.is_le(b, 57))def is_space(+b: U32) -> Bool: Bool.or(Bool.or(U32.is_eq(b, 32), U32.is_eq(b, 10)), Bool.or(U32.is_eq(b, 13), U32.is_eq(b, 9)))def hex_val(+b: U32) -> U32: Bool.pick(U32, is_digit(b), (b - 48 : U32), Bool.pick(U32, Bool.and(U32.is_ge(b, 97), U32.is_le(b, 102)), (b - 87 : U32), Bool.pick(U32, Bool.and(U32.is_ge(b, 65), U32.is_le(b, 70)), (b - 55 : U32), 16)))# a finished string: its bytes (last first), decodeddef str_done(r: Result<&2, &2, U32, List<&2, U32>>, p: List<&2, Ev>) -> List<&2, Ev>: match r: case Done{cs}: EVal{JStr{cs}} <> p case Fail{at}: EBad{"a string that is not UTF-8"} <> p# a byte between tokensdef when(c: Bool, yes: Unit -> St, no: Unit -> St) -> St: match c: case True{}: yes(Unit{}) case False{}: no(Unit{})def top(+b: U32, +p: List<&2, Ev>) -> St: when(U32.is_eq(b, 34), u => St{XStr{[]}, p}, u => when(Bool.or(is_space(b), Bool.or(U32.is_eq(b, 44), U32.is_eq(b, 58))), u => St{XTop{}, p}, u => when(is_digit(b), u => St{XNum{(b - 48 : U32), True{}}, p}, u => when(U32.is_eq(b, 91), u => St{XTop{}, EOpenA{} <> p}, u => when(U32.is_eq(b, 123), u => St{XTop{}, EOpenO{} <> p}, u => when(U32.is_eq(b, 93), u => St{XTop{}, ECloseA{} <> p}, u => when(U32.is_eq(b, 125), u => St{XTop{}, ECloseO{} <> p}, u => when(U32.is_eq(b, 45), u => St{XNum{0, False{}}, p}, u => when(U32.is_eq(b, 116), u => St{XLit{[114, 117, 101], JBool{True{}}}, p}, u => when(U32.is_eq(b, 102), u => St{XLit{[97, 108, 115, 101], JBool{False{}}}, p}, u => when(U32.is_eq(b, 110), u => St{XLit{[117, 108, 108], JNull{}}, p}, u => St{XTop{}, EBad{"an unexpected byte"} <> p})))))))))))def num_more(+b: U32, +v: U32, +int: Bool, +p: List<&2, Ev>) -> St: when(is_digit(b), u => St{XNum{((v * 10 : U32) + (b - 48 : U32) : U32), Bool.and(int, U32.is_le(v, 429496728))}, p}, u => when(Bool.or(Bool.or(U32.is_eq(b, 46), U32.is_eq(b, 101)), Bool.or(U32.is_eq(b, 69), Bool.or(U32.is_eq(b, 43), U32.is_eq(b, 45)))), u => St{XNum{v, False{}}, p}, u => top(b, EVal{JNum{v, int}} <> p)))def lit_next(ok: Bool, t: List<&2, U32>, val: J, p: List<&2, Ev>) -> St: match ok: case True{}: St{XLit{t, val}, p} case False{}: St{XTop{}, EBad{"a misspelled true, false or null"} <> p}def lit_more(rest: List<&2, U32>, +b: U32, val: J, p: List<&2, Ev>) -> St: match rest: case []: top(b, EVal{val} <> p) case c <> t: lit_next(U32.is_eq(b, c), t, val, p)def esc(+b: U32, +bs: List<&2, U32>, +p: List<&2, Ev>) -> St: when(U32.is_eq(b, 117), u => St{XHex{bs, 4, 0, 0}, p}, u => St{XStr{Bool.pick(U32, U32.is_eq(b, 110), 10, Bool.pick(U32, U32.is_eq(b, 116), 9, Bool.pick(U32, U32.is_eq(b, 114), 13, Bool.pick(U32, U32.is_eq(b, 98), 8, Bool.pick(U32, U32.is_eq(b, 102), 12, b))))) <> bs}, p})# four hex digits read: a high surrogate waits for its low half; a low half joins a waiting high onedef hex_done(+v: U32, +hi: U32, +bs: List<&2, U32>, +p: List<&2, Ev>) -> St: when(Bool.and(U32.is_eq(hi, 0), Bool.and(U32.is_ge(v, 55296), U32.is_le(v, 56319))), u => St{XLow{bs, v}, p}, u => when(Bool.xor(U32.is_ne(hi, 0), Bool.and(U32.is_ge(v, 56320), U32.is_le(v, 57343))), u => St{XStr{bs}, EBad{"a lone surrogate escape"} <> p}, u => when(U32.is_ne(hi, 0), u => St{XStr{List.append(&2, U32, List.reverse(&2, U32, U.enc1((65536 + ((((hi - 55296 : U32) * 1024 : U32) + (v - 56320 : U32) : U32)) : U32))), bs)}, p}, u => St{XStr{List.append(&2, U32, List.reverse(&2, U32, U.enc1(v)), bs)}, p})))def hex(+b: U32, +bs: List<&2, U32>, +left: U32, +v: U32, +hi: U32, +p: List<&2, Ev>) -> St: when(U32.is_eq(hex_val(b), 16), u => St{XStr{bs}, EBad{"a bad \\u escape"} <> p}, u => when(U32.is_eq(left, 1), u => hex_done(((v * 16 : U32) + hex_val(b) : U32), hi, bs, p), u => St{XHex{bs, (left - 1 : U32), ((v * 16 : U32) + hex_val(b) : U32), hi}, p}))def in_str(+b: U32, +bs: List<&2, U32>, +p: List<&2, Ev>) -> St: when(U32.is_eq(b, 34), u => St{XTop{}, str_done(U.decode(List.reverse(&2, U32, bs)), p)}, u => when(U32.is_eq(b, 92), u => St{XEsc{bs}, p}, u => St{XStr{b <> bs}, p}))def step_lx(lx: Lx, +b: U32, +p: List<&2, Ev>) -> St: match lx: case XTop{}: top(b, p) case XStr{bs}: in_str(b, bs, p) case XEsc{bs}: esc(b, bs, p) case XHex{bs, left, v, hi}: hex(b, bs, left, v, hi, p) case XLow{+bs, +hi}: when(U32.is_eq(b, 92), u => St{XLowU{bs, hi}, p}, u => St{XStr{bs}, EBad{"a lone surrogate escape"} <> p}) case XLowU{+bs, +hi}: when(U32.is_eq(b, 117), u => St{XHex{bs, 4, 0, hi}, p}, u => St{XStr{bs}, EBad{"a lone surrogate escape"} <> p}) case XNum{v, int}: num_more(b, v, int, p) case XLit{rest, val}: lit_more(rest, b, val, p)def step(s: St, +b: U32) -> St: match s: case St{lx, p}: step_lx(lx, b, p)def run(bs: List<&2, U32>, s: St) -> St: match bs: case []: s case +b <> t: run(t, step(s, b))def is_nil_u(xs: List<&2, U32>) -> Bool: match xs: case []: True{} case x <> t: False{}def lit_end(done: Bool, val: J, p: List<&2, Ev>) -> List<&2, Ev>: match done: case True{}: EVal{val} <> p case False{}: EBad{"the text ends inside a literal"} <> pdef end_lx(lx: Lx, p: List<&2, Ev>) -> List<&2, Ev>: match lx: case XTop{}: p case XNum{v, int}: EVal{JNum{v, int}} <> p case XLit{rest, val}: lit_end(is_nil_u(rest), val, p) case XStr{bs}: EBad{"the text ends inside a string"} <> p case XEsc{bs}: EBad{"the text ends inside a string"} <> p case XHex{bs, left, v, hi}: EBad{"the text ends inside a string"} <> p case XLow{bs, hi}: EBad{"the text ends inside a string"} <> p case XLowU{bs, hi}: EBad{"the text ends inside a string"} <> pdef is_nil_f(xs: List<&2, Fr>) -> Bool: match xs: case []: True{} case x <> t: False{}def result3(top: Maybe<&2, J>) -> Result<&2, &2, String, J>: match top: case None{}: Fail{"no value"} case Some{v}: Done{v}def result2(bad: Maybe<&2, String>, closed: Bool, top: Maybe<&2, J>) -> Result<&2, &2, String, J>: match bad closed: case Some{why} _: Fail{why} case None{} False{}: Fail{"the text ends inside an array or object"} case None{} True{}: result3(top)def result(p: Ps) -> Result<&2, &2, String, J>: match p: case Ps{stack, top, bad}: result2(bad, is_nil_f(stack), top)def events(s: St) -> List<&2, Ev>: match s: case St{lx, p}: List.reverse(&2, Ev, end_lx(lx, p))# the events of bs, in orderdef lex(bs: List<&2, U32>) -> List<&2, Ev>: events(run(bs, St{XTop{}, []}))# the parser, one event at a timedef apply(p: Ps, e: Ev) -> Ps: match e: case EOpenA{}: open(p, FArr{[]}) case EOpenO{}: open(p, FObj{[], None{}}) case ECloseA{}: close(p, True{}) case ECloseO{}: close(p, False{}) case EVal{v}: add(p, v) case EBad{why}: p_bad(why, p)def fold(es: List<&2, Ev>, p: Ps) -> Ps: match es: case []: p case e <> t: fold(t, apply(p, e))def parse_events(es: List<&2, Ev>) -> Result<&2, &2, String, J>: result(fold(es, Ps{[], None{}, None{}}))# the JSON value of bs, or why it is not onedef parse(bs: List<&2, U32>) -> Result<&2, &2, String, J>: parse_events(lex(bs))# ---- reading a parsed value ----def key_is(k: List<&2, U32>, s: String) -> Bool: match k s: case Nil{} SNil{}: True{} case +a <> t SCon{c, r}: Bool.and(U32.is_eq(a, Char.to_u32(c)), key_is(t, r)) case Nil{} SCon{c, r}: False{} case a <> t SNil{}: False{}def field_pick(hit: Bool, v: J, rest: Unit -> Maybe<&2, J>) -> Maybe<&2, J>: match hit: case True{}: Some{v} case False{}: rest(Unit{})def field_go(kvs: List<&2, KV>, +name: String) -> Maybe<&2, J>: match kvs: case []: None{} case KV{k, v} <> t: field_pick(key_is(k, name), v, u => field_go(t, name))# an object's field, if the value is an object and has itdef field(v: J, +name: String) -> Maybe<&2, J>: match v: case JObj{kvs}: field_go(kvs, name) case JNull{}: None{} case JBool{b}: None{} case JNum{n, i}: None{} case JStr{s}: None{} case JArr{xs}: None{}# ---- parsing in parallel ----# A raw newline never occurs inside a JSON token (strings must escape it), so text cut just after newlines lexes# piece by piece to the same events, and the pieces can be lexed at the same time. The text is cut into blocks of# 2^16 bytes by count (any size gives the same events: LAWS.bend); block i's lexer starts after its first newline (block 0's at its start) and runs on through# block i + 1 up to and including that block's first newline, so the pieces it lexes start and end at newlines.def blocks(fuel: Nat, +size: Nat, bs: List<&2, U32>) -> List<&2, List<&2, U32>>: match fuel bs: case _ Nil{}: [] case 0n b <> t: [b <> t] case 1n+f +b <> +t: List.take(&2, U32, b <> t, size) <> blocks(f, size, List.drop(&2, U32, b <> t, size))# the bytes up to and including the first newlinedef line_if(nl: Bool, +b: U32, more: Unit -> List<&2, U32>) -> List<&2, U32>: match nl: case True{}: [b] case False{}: b <> more(Unit{})def head_line(bs: List<&2, U32>) -> List<&2, U32>: match bs: case []: [] case +b <> t: line_if(U32.is_eq(b, 10), b, u => head_line(t))# the bytes after the first newline ([] when there is none: the block is inside one line, lexed by the block before)def after_if(nl: Bool, t: List<&2, U32>, more: Unit -> List<&2, U32>) -> List<&2, U32>: match nl: case True{}: t case False{}: more(Unit{})def after_line(bs: List<&2, U32>) -> List<&2, U32>: match bs: case []: [] case +b <> +t: after_if(U32.is_eq(b, 10), t, u => after_line(t))def start_of(first: Bool, b: List<&2, U32>) -> List<&2, U32>: match first: case True{}: b case False{}: after_line(b)def nl_or(nl: Bool, more: Unit -> Bool) -> Bool: match nl: case True{}: True{} case False{}: more(Unit{})def has_nl(bs: List<&2, U32>) -> Bool: match bs: case []: False{} case +b <> +t: nl_or(U32.is_eq(b, 10), u => has_nl(t))def tail_if(nl: Bool, +b: List<&2, U32>, st: St, more: St -> St) -> St: match nl: case True{}: run(head_line(b), st) case False{}: more(run(b, st))# on through the following blocks up to and including the first newline (a block without one is lexed whole)def tail_run(bs: List<&2, List<&2, U32>>, st: St) -> St: match bs: case []: st case +b <> t: tail_if(has_nl(b), b, st, s => tail_run(t, s))# one block's events: from its start (first) or after its first newline, on through the following blocks to the# next newline; a block with no newline lexes nothing (the block before it lexes it)def lex_owned(owns: Bool, first: Bool, b: List<&2, U32>, rest: List<&2, List<&2, U32>>) -> List<&2, Ev>: match owns: case True{}: events(tail_run(rest, run(start_of(first, b), St{XTop{}, []}))) case False{}: []def lex_block(+first: Bool, +b: List<&2, U32>, rest: List<&2, List<&2, U32>>) -> List<&2, Ev>: lex_owned(Bool.or(first, has_nl(b)), first, b, rest)# blocks i .. i + n (their successors alongside), halves lexed at the same time, depth times overdef seq_blocks(n: Nat, +first: Bool, bs: List<&2, List<&2, U32>>) -> List<&2, Ev>: match n bs: case 0n _: [] case _ Nil{}: [] case 1n+m +b <> +t: List.append(&2, Ev, lex_block(first, b, t), seq_blocks(m, False{}, t))def half_go(n: Nat, +odd: Bool, +acc: Nat) -> Nat: match n: case 0n: acc case 1n+m: half_go(m, Bool.not(odd), Bool.pick(Nat, odd, 1n+acc, acc))def half(n: Nat) -> Nat: half_go(n, False{}, 0n)# events in a tree of lists, so the halves' results join without copyingtype ET is Data: ELeaf{es: List<&2, Ev>} ENode{l: ET, r: ET}def par_blocks(depth: Nat, +n: Nat, +first: Bool, +bs: List<&2, List<&2, U32>>) -> ET: match depth: case 0n: ELeaf{seq_blocks(n, first, bs)} case 1n+ +d: a c = par_blocks(d, half(n), first, bs) par_blocks(d, Nat.sub(n, half(n)), Bool.and(first, Nat.is_eq(half(n), 0n)), List.drop(&2, List<&2, U32>, bs, half(n))) ENode{a, c}def fold_tree(t: ET, p: Ps) -> Ps: match t: case ELeaf{es}: fold(es, p) case ENode{l, r}: fold_tree(r, fold_tree(l, p))# n / 2, rounded down: every second step countsdef par_events(+bs: List<&2, List<&2, U32>>) -> ET: par_blocks(7n, List.length(&2, List<&2, U32>, bs), True{}, bs)# parse text given as blocks (as Tok.open reads a file), the blocks lexed at the same timedef parse_blocks(+bs: List<&2, List<&2, U32>>) -> Result<&2, &2, String, J>: result(fold_tree(par_events(bs), Ps{[], None{}, None{}}))# parse, with the lexing spread over the CPU's threadsdef parse_par(+bs: List<&2, U32>) -> Result<&2, &2, String, J>: parse_blocks(blocks(List.length(&2, U32, bs), 65536n, bs))