Initial Commit

This commit is contained in:
SoraKatadzuma committed 2026-11-10 12:26:50 -06:00
commit 946f600be2
1624 files changed
+43408

No files matched your search

+652
View File
@@ -0,0 +1,652 @@
#! @file document.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the parsed document, which holds every value of JSON text as a flat
#! array of nodes, and `json::value`, which reads one of them.
module std::json;
#! The kinds of JSON values.
pub enum kind: u8 {
empty, #! `null`.
boolean, #! `true` or `false`.
number, #! A number.
text, #! A string.
array, #! A list of values, in order.
object, #! Members, each a key and a value.
}
# What a node is: the kinds of values, then a member's name.
enum node_kind: u8 {
empty,
boolean,
number,
text,
array,
object,
key,
}
# One value of a document, or a member's name, in 16 bytes.
#
# A value's nodes follow it, so an array's elements follow it in order, and an
# object's members do, each as its key and then its value. A container's `length`
# is how many elements or members it holds, and its `next` is the index just past
# everything it holds, so a value is skipped in one step. A string's `start` is
# where its opening quote is, and its text follows that for `length` bytes, unless
# it holds escapes: then its decoded text is in the document's buffer, from `next`.
struct node {
var kind: node_kind;
var flag: u8; #! Whether a string holds escapes, or a boolean is true.
var spare: u16;
var start: u32; #! The byte of the text the value begins at.
var length: u32;
var next: u32;
}
#! JSON text read whole, every value of it held as a node of a flat array.
#!
#! A document views the text it was parsed from, which must outlive it, and the
#! values it gives view the document, so they are good only while it lives. A
#! string holding escapes is decoded once, as the document is parsed, so reading
#! any string allocates nothing.
pub struct document : serial::decoder, moveable {
var _text: strview;
var _nodes: vector<node>;
var _decoded: string; #! The text of each string that holds escapes, decoded.
}
#! A value of a document, by its place in it. It is good only while the document
#! lives and stays where it is.
#!
#! A value writes itself through any format, as `serial::encode` writes a typed
#! value, so a document's values are written again whole.
pub struct value : serial::encodable {
var _document: *document;
var _at: u32;
}
#! A member of an object, as `value::members` gives each.
pub struct member {
pub var key: strview; #! The member's key, still escaped where it holds escapes.
pub var value: value; #! Its value.
}
#! Reads JSON text whole into a document.
#! @param text The text, which must outlive the document and every value of
#! it.
#! @param depth How deep values may nest before parsing fails with `too_deep`.
#! @param alloc An optional allocator for the document to take memory from.
#! @returns The document, or why the text is not JSON, with where it fails.
pub def parse(text: strview, depth: u32 = default_depth, alloc: maybe<&mut allocator> = nothing {}): result<document, error> {
if text.length > 0xFFFFFFFFu {
return error { kind = error_kind::too_long };
}
var made := document {
_text = text,
_nodes = vector::<node>::new(alloc),
_decoded = string::new(alloc)
};
# The open objects and arrays, by their nodes.
var open := vector::<u32>::new(alloc);
var tokens := reader::new(text, depth);
while tokens.next() is some(read) {
val at := read.offset as u32;
match read.kind {
begin_object => {
made.count_in(&open);
open.append(made._nodes.length as u32);
made._nodes.append(node { kind = node_kind::object, start = at });
}
begin_array => {
made.count_in(&open);
open.append(made._nodes.length as u32);
made._nodes.append(node { kind = node_kind::array, start = at });
}
end_object, end_array => {
val closing: u32 = open.at(open.length - 1);
made._nodes.at(closing as u64).next = made._nodes.length as u32;
open.remove_at(open.length - 1);
}
key => {
val holder: u32 = open.at(open.length - 1);
made._nodes.at(holder as u64).length++;
made.add_string(node_kind::key, &read);
}
text => {
made.count_in(&open);
made.add_string(node_kind::text, &read);
}
number => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::number, start = at, length = read.view.length as u32 });
}
boolean => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::boolean, flag = read.truth ? 1 : 0, start = at });
}
empty => {
made.count_in(&open);
made._nodes.append(node { kind = node_kind::empty, start = at });
}
}
}
if tokens.error is some(failed) {
return failed;
}
return move(made);
}
#! Creates a document by taking another's nodes and decoded text, which leaves
#! the other holding nothing.
#! @param other The document to move from.
#! @returns The document, which views the same text.
pub def document::move_of(other: &mut document): document {
return document {
_text = other._text,
_nodes = move(other._nodes),
_decoded = move(other._decoded)
};
}
#! The value the text holds, which holds the rest.
#! @param this The document to read.
#! @returns The value.
pub val document::root: value {
get => value { _document = this as *document, _at = 0 };
}
#! The text the document was parsed from.
#! @param this The document to ask.
#! @returns The text.
pub val document::text: strview {
get => this._text;
}
#! What kind of value the value is.
#! @param this The value to ask.
#! @returns Its kind.
pub val value::kind: kind {
get => (*this._document).kind_at(this._at);
}
#! Whether the value is `null`.
#! @param this The value to ask.
#! @returns Whether it is.
pub val value::is_null: bool {
get => this.kind == kind::empty;
}
#! How many elements an array holds, or members an object holds, repeats
#! included.
#! @param this The value to measure.
#! @returns The count, which is 0 for any other value.
pub val value::length: u64 {
get => (*this._document).count(this._at);
}
#! Where the value begins in the text, by its line and its column.
#! @param this The value to place.
#! @returns Where it is.
pub val value::place: serial::place {
get => (*this._document).place(this._at);
}
#! Finds the first member of an object with a name.
#! @param this The object to look in, which an object is searched member by
#! member.
#! @param key The name to look for, as it is decoded.
#! @returns The member's value, or `nothing` where the value is not an object or
#! has no member of the name.
pub def value::get(&this, key: strview): maybe<value> {
val found := (*this._document).member(this._at, key) else { return nothing {}; };
return value { _document = this._document, _at = found };
}
#! Iterates over the values of every member of an object with a name, in the
#! order they are written, since a name may be given more than once.
#! @param this The object to look in.
#! @param key The name to look for, as it is decoded.
#! @returns An iterator over the values, which gives none where the value is not
#! an object.
pub def value::get_all(&this, key: strview): value::match_cursor {
val count := (*this._document).count(this._at);
val first: u32 = count == 0 ? 0 : this._at + 1;
return value::match_cursor { _document = this._document, _at = first, _left = count, _key = key };
}
#! Finds an element of an array by its index.
#! @param this The array to look in.
#! @param index The element's index, counted from 0.
#! @returns The element, or `nothing` where the value is not an array or is
#! shorter.
pub def value::at(&this, index: u64): maybe<value> {
if this.kind != kind::array || index >= this.length {
return nothing {};
}
return value { _document = this._document, _at = (*this._document).element(this._at, index) };
}
#! Iterates over the elements of an array, in order.
#! @param this The array to walk.
#! @returns An iterator over them, which gives none where the value is not an
#! array.
pub def value::elements(&this): value::element_cursor {
if this.kind != kind::array {
return value::element_cursor { _document = this._document };
}
return value::element_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
}
#! Iterates over the members of an object, in the order they are written,
#! repeats included.
#! @param this The object to walk.
#! @returns An iterator over them, which gives none where the value is not an
#! object.
pub def value::members(&this): value::member_cursor {
if this.kind != kind::object {
return value::member_cursor { _document = this._document };
}
return value::member_cursor { _document = this._document, _at = this._at + 1, _left = this.length };
}
#! Reads a boolean.
#! @param this The value to read.
#! @returns Its truth, or `wrong_kind` where it is not a boolean.
pub def value::as_bool(&this): result<bool, error> {
return (*this._document).as_bool(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as a signed integer, exactly.
#! @param this The value to read.
#! @returns The integer, or `wrong_kind` where it is not a number without a
#! fraction, or `out_of_range` where it does not fit.
pub def value::as_i64(&this): result<i64, error> {
return (*this._document).as_i64(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as an unsigned integer, exactly.
#! @param this The value to read.
#! @returns The integer, or `wrong_kind` where it is not a number without a
#! fraction, or `out_of_range` where it is negative or does not fit.
pub def value::as_u64(&this): result<u64, error> {
return (*this._document).as_u64(this._at) else (e) { return error::from(&e); };
}
#! Reads a number as the nearest 64-bit float.
#! @param this The value to read.
#! @returns The float, or `wrong_kind` where it is not a number, or
#! `out_of_range` where it is too large for 64 bits.
pub def value::as_f64(&this): result<f64, error> {
return (*this._document).as_f64(this._at) else (e) { return error::from(&e); };
}
#! Reads a string, decoded.
#! @param this The value to read.
#! @returns A view of its text, good while the document lives, or `wrong_kind`
#! where it is not a string.
pub def value::as_text(&this): result<strview, error> {
return (*this._document).as_text(this._at) else (e) { return error::from(&e); };
}
#! Writes the value and everything it holds through a format. A number is
#! written as an integer where it is one that fits, and as the nearest float
#! otherwise.
#! @param this The value to write.
#! @param out The format to write it through.
pub def value::encode(&this, out: &mut serial::encoder): void {
match this.kind {
empty => out.empty();
boolean => out.boolean((*this._document).node_at(this._at).flag != 0);
text => out.text((*this._document).text_at(this._at));
number => this.encode_number(out);
array => {
out.begin_array(this.length);
for item in this.elements() {
item.encode(out);
}
out.end_array();
}
object => {
out.begin_object(this.length);
for each in this.members() {
out.member(each.key);
each.value.encode(out);
}
out.end_object();
}
}
}
# Writes a number as an integer where it is one that fits, and otherwise as the
# nearest float, or as nothing where it is too large for one, keeping the failure.
def value::encode_number(&this, out: &mut serial::encoder): void {
# Read once as an integer, since asking for one that is not makes an error, and
# working out where it is reads the text up to it.
val read := serial::integral_of((*this._document).number_at(this._at));
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
if read.whole && read.fits && read.magnitude <= limit {
out.signed(read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64);
return;
}
if read.whole && read.fits && !read.negative {
out.unsigned(read.magnitude);
return;
}
match (*this._document).as_f64(this._at) {
value(real) => out.real(real);
error(_) => {
out.fail(serial::error_kind::out_of_range);
out.empty();
}
}
}
#! An iterator over an array's elements.
pub struct value::element_cursor : iter<value> {
var _document: *document;
var _at: u32;
var _left: u64;
}
#! Gives the next element of the array.
#! @param this The iterator to advance.
#! @returns The next element, or `nothing` once there are no more.
pub def value::element_cursor::next(&mut this): maybe<value> {
if this._left == 0 {
return nothing {};
}
val made := value { _document = this._document, _at = this._at };
this._at = (*this._document).after(this._at);
this._left--;
return made;
}
#! An iterator over an object's members.
pub struct value::member_cursor : iter<member> {
var _document: *document;
var _at: u32; #! The next member's key.
var _left: u64;
}
#! Gives the next member of the object, in the order the text writes them.
#! @param this The iterator to advance.
#! @returns The next member, or `nothing` once there are no more.
pub def value::member_cursor::next(&mut this): maybe<member> {
if this._left == 0 {
return nothing {};
}
val made := member {
key = (*this._document).text_at(this._at),
value = value { _document = this._document, _at = this._at + 1 }
};
this._at = (*this._document).after(this._at + 1);
this._left--;
return made;
}
#! An iterator over the values of an object's members of one name.
pub struct value::match_cursor : iter<value> {
var _document: *document;
var _at: u32; #! The next member's key.
var _left: u64;
var _key: strview;
}
#! Gives the value of the next member of the name.
#! @param this The iterator to advance.
#! @returns The next value, or `nothing` once no member left has the name.
pub def value::match_cursor::next(&mut this): maybe<value> {
while this._left > 0 {
val key := this._at;
this._at = (*this._document).after(key + 1);
this._left--;
if (*this._document).text_at(key) == this._key {
return value { _document = this._document, _at = key + 1 };
}
}
return nothing {};
}
#! What kind of value a node is.
#! @param this The document to read.
#! @param at The value's index.
#! @returns Its kind.
pub def document::kind_of(&this, at: u32): serial::kind {
return (this.kind_at(at) as u8) as serial::kind;
}
#! Finds the value of the first member of an object with a name.
#! @param this The document to read.
#! @param at The object's index.
#! @param name The name to look for, as it is decoded.
#! @returns The member's value's index, or `nothing` where there is none of the
#! name or the value is not an object.
pub def document::member(&this, at: u32, name: strview): maybe<u32> {
if this.node_at(at).kind != node_kind::object {
return nothing {};
}
var key := at + 1;
for _ in 0..this.node_at(at).length as u64 {
if this.text_at(key) == name {
return key + 1;
}
key = this.after(key + 1);
}
return nothing {};
}
#! How many elements an array holds, or members an object holds, repeats
#! included.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The count, which is 0 for any other value.
pub def document::count(&this, at: u32): u64 {
val held := this.node_at(at);
if held.kind != node_kind::array && held.kind != node_kind::object {
return 0;
}
return held.length as u64;
}
#! The name of the member of an object whose value is given.
#! @param this The document to read.
#! @param value The member's value's index.
#! @returns The name, decoded.
pub def document::name_of(&this, value: u32): strview {
return this.text_at(value - 1);
}
#! The element of an array, or the value of a member of an object, after
#! another.
#! @param this The document to read.
#! @param at The array's or object's index.
#! @param previous The element or value before, which must not be the last.
#! @returns The value's index.
pub def document::next_element(&this, at: u32, previous: u32): u32 {
val next := this.after(previous);
return this.node_at(at).kind == node_kind::object ? next + 1 : next;
}
#! An element of an array, or the value of a member of an object, by its index.
#! @param this The document to read.
#! @param at The array's or object's index.
#! @param index Which element or member, which must be less than the count.
#! @returns The value's index.
pub def document::element(&this, at: u32, index: u64): u32 {
val object := this.node_at(at).kind == node_kind::object;
var held := object ? at + 2 : at + 1;
for _ in 0..index {
held = this.after(held);
if object {
held++;
}
}
return held;
}
#! Reads a string's text, decoded.
#! @param this The document to read.
#! @param at The value's index.
#! @returns A view of the text, or `wrong_kind` where the value is not a string.
pub def document::as_text(&this, at: u32): result<strview, serial::error> {
if this.node_at(at).kind != node_kind::text {
return this.wrong(at);
}
return this.text_at(at);
}
#! Reads a value as a signed integer, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `i64` holds.
pub def document::as_i64(&this, at: u32): result<i64, serial::error> {
val read := this.integral_at(at) else (e) { return e; };
val limit: u64 = read.negative ? 0x8000000000000000u : 0x7FFFFFFFFFFFFFFFu;
if !read.fits || read.magnitude > limit {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return read.negative ? (0 - read.magnitude) as i64 : read.magnitude as i64;
}
#! Reads a value as an unsigned integer, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The integer, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is not an integer `u64` holds.
pub def document::as_u64(&this, at: u32): result<u64, serial::error> {
val read := this.integral_at(at) else (e) { return e; };
if !read.fits || (read.negative && read.magnitude != 0) {
return serial::error::at(serial::error_kind::out_of_range, this.place(at));
}
return read.magnitude;
}
#! Reads a value as a real number, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The number, or `wrong_kind` where the value is not a number, or
#! `out_of_range` where it is too large for an `f64`.
pub def document::as_f64(&this, at: u32): result<f64, serial::error> {
if this.node_at(at).kind != node_kind::number {
return this.wrong(at);
}
match real::parse::<f64>(this.number_at(at)) {
value(read) => return read;
error(&_) => return serial::error::at(
serial::error_kind::out_of_range, this.place(at));
}
return 0.0;
}
#! Reads a value as `true` or `false`, as `serial::decode` does.
#! @param this The document to read.
#! @param at The value's index.
#! @returns The value, or `wrong_kind` where it is not a boolean.
pub def document::as_bool(&this, at: u32): result<bool, serial::error> {
val held := this.node_at(at);
if held.kind != node_kind::boolean {
return this.wrong(at);
}
return held.flag != 0;
}
#! Where a value begins in the text, by its line and its column.
#! @param this The document to read.
#! @param at The value's index.
#! @returns Where it is.
pub def document::place(&this, at: u32): serial::place {
return serial::place_of(this._text, this.node_at(at).start as u64);
}
# Counts a value as an element of the innermost open array; an object counts its
# members by their keys.
def document::count_in(&mut this, open: &vector<u32>): void {
if open.length == 0 {
return;
}
val holder: u32 = open.at(open.length - 1);
if this._nodes.at(holder as u64).kind == node_kind::array {
this._nodes.at(holder as u64).length++;
}
}
# Adds a string or key, decoding its escapes into the buffer where it holds any.
def document::add_string(&mut this, kind: node_kind, read: &token): void {
if !read.escaped {
this._nodes.append(node { kind = kind, start = read.offset as u32, length = read.view.length as u32 });
return;
}
val from := this._decoded.length;
unescape(read.view, &mut this._decoded);
this._nodes.append(node {
kind = kind,
flag = 1,
start = read.offset as u32,
length = (this._decoded.length - from) as u32,
next = from as u32
});
}
def document::node_at(&this, at: u32): &node {
return this._nodes.at(at as u64);
}
def document::kind_at(&this, at: u32): kind {
val held := this.node_at(at).kind;
return held == node_kind::key ? kind::text : (held as u8) as kind;
}
# The index just past a value and everything it holds.
def document::after(&this, at: u32): u32 {
val held := this.node_at(at);
if held.kind == node_kind::array || held.kind == node_kind::object {
return held.next;
}
return at + 1;
}
# A string's or key's text, decoded.
def document::text_at(&this, at: u32): strview {
val held := this.node_at(at);
if held.flag != 0 {
return this._decoded.substr(held.next as u64, held.length as u64);
}
return this._text.substr(held.start as u64 + 1, held.length as u64);
}
# A number's text.
def document::number_at(&this, at: u32): strview {
val held := this.node_at(at);
return this._text.substr(held.start as u64, held.length as u64);
}
# A number read as an integer exactly, or why it is not one.
def document::integral_at(&this, at: u32): result<serial::integral, serial::error> {
if this.node_at(at).kind != node_kind::number {
return this.wrong(at);
}
val read := serial::integral_of(this.number_at(at));
if !read.whole {
return this.wrong(at);
}
return read;
}
def document::wrong(&this, at: u32): serial::error {
return serial::error::at(serial::error_kind::wrong_kind, this.place(at));
}