#! @file reader.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the pull reader, which reads JSON one token at a time, checking it as #! it goes, without building anything. import core::swar; module std::json; #! The nesting a reader allows when it is given no other limit. pub const default_depth: u32 = 512; #! What a token is. pub enum token_kind: u8 { begin_object, #! `{`, which begins an object. end_object, #! `}`, which ends one. begin_array, #! `[`, which begins an array. end_array, #! `]`, which ends one. key, #! A member's name, whose value is the next token. text, #! A string. number, #! A number, whose text is its view. boolean, #! `true` or `false`, which `truth` says. empty, #! `null`. } #! A piece of JSON a reader gives. pub struct token { pub var kind: token_kind; #! What the token is. pub var escaped: bool; #! Whether a key's or text's view holds escapes, which `unescape` decodes. pub var truth: bool; #! A boolean's value. pub var view: strview; #! A key's or text's text between its quotes, a number's text, or the literal. pub var offset: u64; #! The byte of the text the token begins at. } # What a reader looks for next. enum reading: u8 { value, #! A value: the first, or one after `:` or after `,` within an array. first_element, #! A value or `]`, after `[`. first_member, #! A key or `}`, after `{`. member, #! A key, after `,` within an object. colon, #! The `:` after a key. after, #! A `,` or the end of what holds the value just read. done, #! Nothing but whitespace, after the whole value. failed, #! Nothing: the reader has stopped at an error. } #! Reads JSON one token at a time, checking it as it goes: commas, colons, #! nesting, escapes, UTF-8, and the grammar of numbers. It stops at the first #! error, which `error` then gives. #! #! A reader views the text it reads, and so do its tokens, so the text outlives #! them. It allocates nothing unless its limit lets values nest past 512 levels. pub struct reader { var _text: strview; var _at: u64; var _state: reading; var _depth: u32; var _limit: u32; var _stack: u64[8]; #! A bit for each of the first 512 open values, set for an object. var _deeper: vector; #! The bits of those past 512. var _error: maybe; } #! Makes a reader of JSON text. #! @param text The text to read, which must outlive the reader and its #! tokens. #! @param depth How deep values may nest before reading fails with `too_deep`. #! @returns The reader, at the start of the text. pub def reader::new(text: strview, depth: u32 = default_depth): reader { return reader { _text = text, _limit = depth }; } #! Why reading stopped before the end of the text, where it did. #! @param this The reader to ask. #! @returns The error, or `nothing` where none has been met. pub val reader::error: maybe { get => this._error; } #! How deep the reader is among open objects and arrays. #! @param this The reader to ask. #! @returns The number of them that are open. pub val reader::depth: u32 { get => this._depth; } #! Reads the next token. #! @param this The reader to read with. #! @returns The token, or `nothing` at the end of the text or at an error, which #! `error` tells apart. pub def reader::next(&mut this): maybe { while true { this.skip_space(); match this._state { value => return this.read_value(); first_element => { if this.peek() != ']' { return this.read_value(); } return this.close(token_kind::end_array); } first_member => { if this.peek() == '}' { return this.close(token_kind::end_object); } return this.read_key(); } member => return this.read_key(); colon => { if this.peek() != ':' { return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at); } this._at++; this._state = reading::value; } after => { if this._depth == 0 { this._state = reading::done; continue; } val byte := this.peek(); if byte == ',' { this._at++; this._state = this.in_object() ? reading::member : reading::value; continue; } if byte == '}' && this.in_object() { return this.close(token_kind::end_object); } if byte == ']' && !this.in_object() { return this.close(token_kind::end_array); } return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at); } done => { if this.at_end() { return nothing {}; } return this.fail(error_kind::trailing_text, this._at); } failed => return nothing {}; } } return nothing {}; } #! Reads past the value whose first token is next, however much it holds, as #! after a key whose value is not wanted. #! @param this The reader to read with. #! @returns Whether the value was read whole, which it is not at an error. pub def reader::skip(&mut this): bool { val outer := this._depth; while this.next() is some(read) { if read.kind == token_kind::key { continue; } if this._depth == outer { return true; } } return false; } # Reads a value: an object or array opening, a string, a number, or a literal. def reader::read_value(&mut this): maybe { if this.at_end() { return this.fail(error_kind::unexpected_end, this._at); } val start := this._at; match this._text[start] { '{' => return this.open(token_kind::begin_object, true); '[' => return this.open(token_kind::begin_array, false); '"' => return this.read_string(token_kind::text); 't' => return this.read_literal("true", token_kind::boolean, true); 'f' => return this.read_literal("false", token_kind::boolean, false); 'n' => return this.read_literal("null", token_kind::empty, false); else => { val byte := this._text[start]; if byte != '-' && !byte.is_digit { return this.fail(error_kind::unexpected_byte, start); } return this.read_number(); } } return nothing {}; } # Reads a key, and the `:` after it is looked for next. def reader::read_key(&mut this): maybe { if this.peek() != '"' { return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at); } val read := this.read_string(token_kind::key); if read is some(_) { this._state = reading::colon; } return read; } # Reads a string from its opening quote, checking its escapes and its UTF-8, and # that it holds no control characters, which JSON writes as escapes. def reader::read_string(&mut this, kind: token_kind): maybe { val start := this._at; var index := start + 1; var escaped := false; while true { index = plain_run(this._text, index); if index >= this._text.length { return this.fail(error_kind::unexpected_end, index); } val byte := this._text[index]; if byte == '"' { break; } if byte == '\\' { val end := escape_end(this._text, index); if end == 0 { return this.fail(error_kind::invalid_escape, index); } escaped = true; index = end; continue; } if byte < 0x20 { return this.fail(error_kind::unexpected_byte, index); } if byte < 0x80 { index++; continue; } val count := serial::utf8_length(this._text, index); if count == 0 { return this.fail(error_kind::invalid_utf8, index); } index += count; } this._at = index + 1; this._state = reading::after; return token { kind = kind, escaped = escaped, view = this._text.substr(start + 1, index - start - 1), offset = start }; } # Reads a number, which must end where a value may: at whitespace, a `,`, a closing # bracket, or the end of the text, so `01` and `1x` are errors of the number. def reader::read_number(&mut this): maybe { val start := this._at; val end := number_end(this._text, start); if end == start || (end < this._text.length && !ends_value(this._text[end])) { return this.fail(error_kind::invalid_number, start); } this._at = end; this._state = reading::after; return token { kind = token_kind::number, view = this._text.substr(start, end - start), offset = start }; } # Reads `true`, `false`, or `null`. def reader::read_literal(&mut this, word: strview, kind: token_kind, truth: bool): maybe { val start := this._at; val found := this._text.substr(start, word.length); if found != word { # Text that ends partway through the word ends early, and anything else is wrong. val cut := found.length < word.length && word.starts_with(found); return this.fail(cut ? error_kind::unexpected_end : error_kind::unexpected_byte, start); } this._at += word.length; this._state = reading::after; return token { kind = kind, truth = truth, view = found, offset = start }; } # Opens an object or array, nesting one level deeper. def reader::open(&mut this, kind: token_kind, object: bool): maybe { val start := this._at; if this._depth >= this._limit { return this.fail(error_kind::too_deep, start); } this.mark(this._depth, object); this._depth++; this._at++; this._state = object ? reading::first_member : reading::first_element; return token { kind = kind, view = this._text.substr(start, 1), offset = start }; } # Closes the innermost object or array, at its closing bracket. def reader::close(&mut this, kind: token_kind): maybe { val start := this._at; this._depth--; this._at++; this._state = reading::after; return token { kind = kind, view = this._text.substr(start, 1), offset = start }; } # Records whether the value open at a level is an object. def reader::mark(&mut this, level: u32, object: bool): void { val bit: u64 = 1u << (level % 64) as u64; if level < 512 { val word := (level / 64) as u64; this._stack[word] = object ? this._stack[word] | bit : this._stack[word] & ~bit; return; } val word := ((level - 512) / 64) as u64; while this._deeper.length <= word { this._deeper.append(0); } val held := this._deeper.at(word); this._deeper.set(word, object ? held | bit : held & ~bit); } # Whether the innermost open value is an object. def reader::in_object(&this): bool { val level := this._depth - 1; val bit: u64 = 1u << (level % 64) as u64; if level < 512 { return (this._stack[(level / 64) as u64] & bit) != 0; } return (this._deeper.at(((level - 512) / 64) as u64) & bit) != 0; } # Stops at an error, which `error` then gives. def reader::fail(&mut this, kind: error_kind, offset: u64): maybe { this._error = error_at(kind, this._text, offset); this._state = reading::failed; return nothing {}; } # Moves past the whitespace JSON allows between tokens. def reader::skip_space(&mut this): void { this._at = space_run(this._text, this._at); while this._at < this._text.length { val byte := this._text[this._at]; if byte != ' ' && byte != '\n' && byte != '\r' && byte != '\t' { return; } this._at++; } } # Past the bytes of a string from a place that need no looking at alone: none # of `"`, `\`, a control character, or a byte past ASCII, which as an `i8` is # below zero, so one comparison finds both. Sixteen at a time where vectors are # held in registers, then eight at a time as words, the last few read without # passing the end. def plain_run(text: strview, from: u64): u64 { var at := from; if lanes_held() { val quote := u8x16::splat('"'); val slash := u8x16::splat('\\'); val below := i8x16::splat(0x20); while at + 16 <= text.length { val chunk := u8x16::load(text, at); val stops := chunk.equal("e).bits() | chunk.equal(&slash).bits() | chunk.bits::().less(&below).bits(); return at + trailing_zeros(stops) as u64 if stops != 0; at += 16; } } val data := text.data; while at + 8 <= text.length { val stops := plain_stops(swar::load(data + at)); return at + stops.first() if stops.any(); at += 8; } if at < text.length { val stops: swar::mask8 = plain_stops(swar::load_last(data + at, text.length - at)) & swar::mask8::leading(text.length - at); return at + stops.first() if stops.any(); } return text.length; } # The bytes of a word a string's plain run stops at. def plain_stops(word: swar::bytes8): swar::mask8 { return word.equal('"') | word.equal('\\') | word.below(0x20) | (word & 0x8080808080808080); } # Past the whitespace from a place, sixteen bytes at a time where vectors are # held in registers, then eight at a time as words where the first byte is # whitespace, as where lines are indented, and none otherwise. def space_run(text: strview, from: u64): u64 { var at := from; if lanes_held() { val blank := u8x16::splat(' '); val newline := u8x16::splat('\n'); val ret := u8x16::splat('\r'); val tab := u8x16::splat('\t'); while at + 16 <= text.length { val chunk := u8x16::load(text, at); val spaces := chunk.equal(&blank).bits() | chunk.equal(&newline).bits() | chunk.equal(&ret).bits() | chunk.equal(&tab).bits(); return at + trailing_zeros(~spaces) as u64 if spaces != 0xFFFF; at += 16; } } return at if at >= text.length || !is_json_space(text[at]); val data := text.data; while at + 8 <= text.length { val word := swar::load(data + at); val other: swar::mask8 = ~(word.equal(' ') | word.equal('\n') | word.equal('\r') | word.equal('\t')) & 0x8080808080808080; return at + other.first() if other.any(); at += 8; } return at; } # Whether a byte is whitespace JSON allows between tokens. def is_json_space(byte: u8): bool { return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t'; } # The byte the reader is at, or 0 at the end of the text. def reader::peek(&this): u8 { return this.at_end() ? 0 : this._text[this._at]; } def reader::at_end(&this): bool { return this._at >= this._text.length; } # Whether a byte may follow a value: whitespace, a `,`, or a closing bracket. def ends_value(byte: u8): bool { return byte == ' ' || byte == '\n' || byte == '\r' || byte == '\t' || byte == ',' || byte == ']' || byte == '}'; } # Where the escape beginning at `at` ends, or 0 where it is not one JSON has: one of # `\" \\ \/ \b \f \n \r \t`, or `\u` and four hexadecimal digits, where a surrogate # is the first of a pair written as two escapes. def escape_end(text: strview, at: u64): u64 { if at + 1 >= text.length { return 0; } val marker := text[at + 1]; if marker == '"' || marker == '\\' || marker == '/' || marker == 'b' || marker == 'f' || marker == 'n' || marker == 'r' || marker == 't' { return at + 2; } if marker != 'u' || !hex_at(text, at + 2) { return 0; } val code := hex_value(text, at + 2); if code >= 0xDC00 && code <= 0xDFFF { return 0; } if code < 0xD800 || code > 0xDBFF { return at + 6; } # A high surrogate is followed by a low one. if at + 7 >= text.length || text[at + 6] != '\\' || text[at + 7] != 'u' || !hex_at(text, at + 8) { return 0; } val low := hex_value(text, at + 8); if low < 0xDC00 || low > 0xDFFF { return 0; } return at + 12; } # Whether four hexadecimal digits begin at `at`. def hex_at(text: strview, at: u64): bool { if at + 4 > text.length { return false; } for index in 0u..4u { if !text[at + index].is_hex { return false; } } return true; }