Files
std/yaml/reader.sakura
T
2026-11-13 21:54:22 -06:00

722 lines
25 KiB
Plaintext

#! @file reader.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the reader, which gives YAML's text as a stream of events: where each
#! document, mapping, and sequence begins and ends, and each scalar and alias. It is
#! built as libyaml's parser is: a state machine over the scanner's tokens, with a
#! stack of its own rather than recursion.
module std::yaml;
#! The kinds of events the reader gives.
pub enum event_kind: u8 {
begin_document, #! The beginning of a document.
end_document, #! Its end.
begin_mapping, #! The beginning of a mapping.
end_mapping, #! Its end.
begin_sequence, #! The beginning of a sequence.
end_sequence, #! Its end.
scalar, #! A scalar, whose text is `text`.
alias, #! An alias, which names the anchor of a node given before it.
}
#! How a scalar or a collection is written.
pub enum style: u8 {
plain, #! A scalar written as it is.
single, #! A scalar in single quotes.
double, #! A scalar in double quotes, with escapes.
literal, #! A block scalar, `|`, keeping its line breaks.
folded, #! A block scalar, `>`, folding its lines.
block, #! A collection written by indentation.
flow, #! A collection written in brackets or braces.
}
#! One event of the stream.
pub struct event {
pub var kind: event_kind; #! What the event is.
pub var style: style; #! A scalar's, or a collection's.
pub var explicit: bool; #! Whether a document's beginning is `---`, or its end `...`.
pub var text: strview; #! A scalar's text, decoded, or the anchor an alias names.
pub var anchor: strview; #! The anchor of a scalar or collection, or empty.
pub var tag: strview; #! Its tag, resolved, as `tag:yaml.org,2002:str`, `!` for the non-specific tag, or empty.
pub var offset: u64; #! The byte of the text it begins at.
}
# What the reader expects next.
enum state: u8 {
stream_start,
implicit_document_start,
document_start,
document_content,
document_end,
block_node,
block_node_or_indentless_sequence,
flow_node,
block_sequence_first_entry,
block_sequence_entry,
indentless_sequence_entry,
block_mapping_first_key,
block_mapping_key,
block_mapping_value,
flow_sequence_first_entry,
flow_sequence_entry,
flow_sequence_entry_mapping_key,
flow_sequence_entry_mapping_value,
flow_sequence_entry_mapping_end,
flow_mapping_first_key,
flow_mapping_key,
flow_mapping_value,
flow_mapping_empty_value,
end,
}
# A handle a `%TAG` directive gives, and its prefix, as the text writes them.
struct handle_prefix {
var handle: strview;
var prefix: strview;
}
#! Reads YAML text as a stream of events, one at a time, checking as it goes.
#!
#! A scalar's text is decoded. Where it needs no decoding, it views the text
#! read, and otherwise the reader's memory, which the next event uses again, so
#! it is good only until the next event. Reading stops at the first error, which
#! `error` gives.
pub struct reader {
var _scanner: scanner;
var _state: state;
var _states: vector<state>;
var _depth: u32;
var _limit: u32;
var _handles: vector<handle_prefix>; #! Those the current document's directives give.
var _tag: string; #! The current event's tag, resolved.
var _versioned: bool; #! Whether the current document's directives gave `%YAML`.
var _ended: bool; #! Whether the last document ended with `...`, after which another may begin without `---`.
var _error: maybe<error>;
}
#! Makes a reader of YAML text.
#! @param text The text, which must outlive the reader.
#! @param depth How deep collections may nest before reading fails with
#! `too_deep`.
#! @returns The reader, which has read nothing yet.
pub def reader::new(text: strview, depth: u32 = default_depth): reader {
var made := reader {
_scanner = scanner::new(text),
_states = vector::<state>::new(),
_limit = depth,
_handles = vector::<handle_prefix>::new(),
_tag = string::new(nothing {})
};
if text.length > 0xFFFFFFFFu {
made._error = error { kind = error_kind::too_long };
return move(made);
}
if first_disallowed(text) is some(bad) {
made._error = error_at(bad.kind, text, bad.offset);
}
return move(made);
}
#! Why reading stopped before the stream's end, where it did.
#! @param this The reader to ask.
#! @returns The error, or `nothing` where none was found.
pub val reader::error: maybe<error> {
get => this._error;
}
#! Reads the next event.
#! @param this The reader to read.
#! @returns The event, or `nothing` once the stream has ended, or an error
#! stopped it, as `error` then says.
pub def reader::next(&mut this): maybe<event> {
if this._error is some(_) || this._state == state::end {
return nothing {};
}
this._tag.clear();
while true {
val made := this.step() else {
if this._scanner._failure is some(failed) {
this.keep(failed);
}
return nothing {};
};
if made.kind != event_kind::scalar || made.offset != 0xFFFFFFFFFFFFFFFFu {
return made;
}
# The stream's beginning and end are not events of their own.
if this._state == state::end {
return nothing {};
}
}
return nothing {};
}
#! Reads past the node whose first event is next, and everything it holds.
#! @param this The reader to read.
#! @returns Whether it was read past, rather than reading failing or the stream
#! ending.
pub def reader::skip(&mut this): bool {
var depth: u64 = 0;
while true {
val read := this.next() else { return false; };
match read.kind {
begin_mapping, begin_sequence, begin_document => depth++;
end_mapping, end_sequence, end_document => depth--;
else => {}
}
if depth == 0 {
return true;
}
}
return true;
}
# A marker the stream's beginning and end give, which `next` reads past.
def reader::stream_marker(): event {
return event { kind = event_kind::scalar, offset = 0xFFFFFFFFFFFFFFFFu };
}
# Keeps the first error.
def reader::keep(&mut this, failed: error): void {
if this._error is none {
this._error = failed;
}
}
# Fails with an error of a kind at a byte of the text.
def reader::fail(&mut this, kind: error_kind, offset: u64): maybe<event> {
this.keep(error_at(kind, this._scanner._text, offset));
return nothing {};
}
# Fails where a token stands that cannot: at the end of the text, the text ends too
# soon, and anywhere else a byte stands where nothing of its kind may.
def reader::unexpected(&mut this, found: &token): maybe<event> {
if found.kind == token_kind::stream_end {
return this.fail(error_kind::unexpected_end, found.start);
}
return this.fail(error_kind::unexpected_byte, found.start);
}
def reader::peek(&mut this): maybe<token> {
return this._scanner.peek();
}
def reader::pop(&mut this): state {
val made := this._states.at(this._states.length - 1);
this._states.remove_at(this._states.length - 1);
return made;
}
# An empty plain scalar, where a node is left out.
def reader::empty(at: u64): event {
return event { kind = event_kind::scalar, style = style::plain, offset = at };
}
# Reads the next event, by what the reader expects.
def reader::step(&mut this): maybe<event> {
return match this._state {
stream_start => this.stream_start(),
implicit_document_start => this.document_start(true),
document_start => this.document_start(false),
document_content => this.document_content(),
document_end => this.document_end(),
block_node => this.node(true, false),
block_node_or_indentless_sequence => this.node(true, true),
flow_node => this.node(false, false),
block_sequence_first_entry => this.block_sequence_entry(true),
block_sequence_entry => this.block_sequence_entry(false),
indentless_sequence_entry => this.indentless_sequence_entry(),
block_mapping_first_key => this.block_mapping_key(true),
block_mapping_key => this.block_mapping_key(false),
block_mapping_value => this.block_mapping_value(),
flow_sequence_first_entry => this.flow_sequence_entry(true),
flow_sequence_entry => this.flow_sequence_entry(false),
flow_sequence_entry_mapping_key => this.flow_sequence_entry_mapping_key(),
flow_sequence_entry_mapping_value => this.flow_sequence_entry_mapping_value(),
flow_sequence_entry_mapping_end => this.flow_sequence_entry_mapping_end(),
flow_mapping_first_key => this.flow_mapping_key(true),
flow_mapping_key => this.flow_mapping_key(false),
flow_mapping_value => this.flow_mapping_value(false),
flow_mapping_empty_value => this.flow_mapping_value(true),
end => nothing {},
};
}
def reader::stream_start(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind != token_kind::stream_start {
return this.unexpected(&read);
}
this._scanner.take();
this._state = state::implicit_document_start;
return reader::stream_marker();
}
# Begins a document: one without `---` where nothing says one must be written, or
# one with its directives and `---`, or ends the stream.
def reader::document_start(&mut this, implicit: bool): maybe<event> {
var read := this.peek() else { return nothing {}; };
# Any number of `...` may end the last document, or stand where none has begun.
while read.kind == token_kind::document_end {
this._ended = true;
this._scanner.take();
read = this.peek() else { return nothing {}; };
}
val bare := read.kind != token_kind::version_directive && read.kind != token_kind::tag_directive
&& read.kind != token_kind::document_start && read.kind != token_kind::stream_end;
if bare && (implicit || this._ended) {
this._handles.clear();
this._ended = false;
this._states.append(state::document_end);
this._state = state::block_node;
return event { kind = event_kind::begin_document, offset = read.start };
}
if read.kind == token_kind::stream_end {
this._scanner.take();
this._state = state::end;
return reader::stream_marker();
}
# Directives may only follow a document that ended with `...`.
if !implicit && !this._ended && read.kind != token_kind::document_start {
return this.unexpected(&read);
}
if !this.directives() {
return nothing {};
}
read = this.peek() else { return nothing {}; };
if read.kind != token_kind::document_start {
return this.unexpected(&read);
}
this._scanner.take();
this._ended = false;
this._states.append(state::document_end);
this._state = state::document_content;
return event { kind = event_kind::begin_document, explicit = true, offset = read.start };
}
# Reads a document's directives, which `%YAML` may be given in once, and `%TAG` once
# for each handle.
def reader::directives(&mut this): bool {
this._handles.clear();
this._versioned = false;
while true {
val read := this.peek() else { return false; };
if read.kind == token_kind::version_directive {
if this._versioned {
this.fail(error_kind::invalid_directive, read.start);
return false;
}
this._versioned = true;
val major := this._scanner.first_of(&read);
if major != "1" {
this.fail(error_kind::unsupported_version, read.start);
return false;
}
this._scanner.take();
continue;
}
if read.kind == token_kind::tag_directive {
val handle := this._scanner.first_of(&read);
if this.prefix_of(handle) is some(_) {
this.fail(error_kind::invalid_directive, read.start);
return false;
}
this._handles.append(handle_prefix { handle = handle, prefix = this._scanner.second_of(&read) });
this._scanner.take();
continue;
}
return true;
}
return true;
}
def reader::document_content(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::version_directive || read.kind == token_kind::tag_directive
|| read.kind == token_kind::document_start || read.kind == token_kind::document_end
|| read.kind == token_kind::stream_end {
this._state = this.pop();
return reader::empty(read.start);
}
return this.node(true, false);
}
def reader::document_end(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
var explicit := false;
if read.kind == token_kind::document_end {
explicit = true;
this._ended = true;
this._scanner.take();
} else if read.kind != token_kind::document_start && read.kind != token_kind::stream_end {
# Only `---`, `...`, or the end may follow a document, so this is what does not fit
# it, as a second node at the top.
return this.unexpected(&read);
}
this._state = state::document_start;
return event { kind = event_kind::end_document, explicit = explicit, offset = read.start };
}
# Reads a node: an alias, or a scalar or collection with its anchor and tag, or an
# empty scalar where only an anchor or a tag is written.
def reader::node(&mut this, block: bool, indentless: bool): maybe<event> {
var read := this.peek() else { return nothing {}; };
if read.kind == token_kind::alias {
this._state = this.pop();
this._scanner.take();
return event { kind = event_kind::alias, text = this._scanner.first_of(&read), offset = read.start };
}
val start := read.start;
var anchor := strview::blank();
var tag := strview::blank();
var tagged := false;
for _ in 0..2 {
if read.kind == token_kind::anchor && anchor.length == 0 {
anchor = this._scanner.first_of(&read);
this._scanner.take();
read = this.peek() else { return nothing {}; };
continue;
}
if read.kind == token_kind::tag && !tagged {
tagged = true;
if !this.resolve_tag(&read) {
return nothing {};
}
this._scanner.take();
read = this.peek() else { return nothing {}; };
continue;
}
}
if tagged {
tag = this._tag.span;
}
val decorated := anchor.length > 0 || tagged;
if indentless && read.kind == token_kind::block_entry {
this._state = state::indentless_sequence_entry;
return this.begin(event_kind::begin_sequence, style::block, anchor, tag, start);
}
if read.kind == token_kind::scalar {
this._state = this.pop();
this._scanner.take();
return event {
kind = event_kind::scalar,
style = read.style,
text = this._scanner.first_of(&read),
anchor = anchor,
tag = tag,
offset = start
};
}
if read.kind == token_kind::flow_sequence_start {
this._state = state::flow_sequence_first_entry;
return this.begin(event_kind::begin_sequence, style::flow, anchor, tag, start);
}
if read.kind == token_kind::flow_mapping_start {
this._state = state::flow_mapping_first_key;
return this.begin(event_kind::begin_mapping, style::flow, anchor, tag, start);
}
if block && read.kind == token_kind::block_sequence_start {
this._state = state::block_sequence_first_entry;
return this.begin(event_kind::begin_sequence, style::block, anchor, tag, start);
}
if block && read.kind == token_kind::block_mapping_start {
this._state = state::block_mapping_first_key;
return this.begin(event_kind::begin_mapping, style::block, anchor, tag, start);
}
if decorated {
this._state = this.pop();
return event { kind = event_kind::scalar, style = style::plain, anchor = anchor, tag = tag, offset = start };
}
return this.unexpected(&read);
}
# Begins a collection, which counts toward how deep collections nest.
def reader::begin(&mut this, kind: event_kind, shape: style, anchor: strview, tag: strview, at: u64): maybe<event> {
this._depth++;
if this._depth > this._limit {
return this.fail(error_kind::too_deep, at);
}
return event { kind = kind, style = shape, anchor = anchor, tag = tag, offset = at };
}
# Ends a collection.
def reader::finish(&mut this, kind: event_kind, at: u64): event {
this._depth--;
return event { kind = kind, offset = at };
}
# Resolves a tag into `_tag`: a verbatim tag as it is, and a shorthand through its
# handle's prefix, with `%` escapes decoded.
def reader::resolve_tag(&mut this, read: &token): bool {
val handle := this._scanner.first_of(read);
val suffix := this._scanner.second_of(read);
if handle.length == 0 {
append_decoded(suffix, &mut this._tag);
return true;
}
if handle == "!" && suffix.length == 0 {
this._tag.push('!');
return true;
}
if this.prefix_of(handle) is some(prefix) {
append_decoded(prefix, &mut this._tag);
append_decoded(suffix, &mut this._tag);
return true;
}
if handle == "!" {
this._tag.push('!');
append_decoded(suffix, &mut this._tag);
return true;
}
if handle == "!!" {
this._tag.append("tag:yaml.org,2002:");
append_decoded(suffix, &mut this._tag);
return true;
}
this.fail(error_kind::unknown_handle, read.start);
return false;
}
# The prefix the current document's directives give a handle, where they give one.
def reader::prefix_of(&this, handle: strview): maybe<strview> {
for each in this._handles {
if each.handle == handle {
return each.prefix;
}
}
return nothing {};
}
# Appends text with its `%` escapes decoded.
def append_decoded(text: strview, into: &mut string): void {
var at: u64 = 0;
while at < text.length {
if text[at] == '%' && at + 2 < text.length {
into.push((text[at + 1].digit_value * 16 + text[at + 2].digit_value) as u8);
at += 3;
continue;
}
into.push(text[at]);
at++;
}
}
def reader::block_sequence_entry(&mut this, first: bool): maybe<event> {
if first {
this._scanner.take();
}
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::block_entry {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::block_entry && next.kind != token_kind::block_end {
this._states.append(state::block_sequence_entry);
return this.node(true, false);
}
this._state = state::block_sequence_entry;
return reader::empty(read.end);
}
if read.kind == token_kind::block_end {
this._state = this.pop();
this._scanner.take();
return this.finish(event_kind::end_sequence, read.start);
}
return this.unexpected(&read);
}
def reader::indentless_sequence_entry(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::block_entry {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::block_entry && next.kind != token_kind::key
&& next.kind != token_kind::value && next.kind != token_kind::block_end {
this._states.append(state::indentless_sequence_entry);
return this.node(true, false);
}
this._state = state::indentless_sequence_entry;
return reader::empty(read.end);
}
this._state = this.pop();
return this.finish(event_kind::end_sequence, read.start);
}
def reader::block_mapping_key(&mut this, first: bool): maybe<event> {
if first {
this._scanner.take();
}
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::key {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::key && next.kind != token_kind::value && next.kind != token_kind::block_end {
this._states.append(state::block_mapping_value);
return this.node(true, true);
}
this._state = state::block_mapping_value;
return reader::empty(read.end);
}
# A value without a key has an empty key.
if read.kind == token_kind::value {
this._state = state::block_mapping_value;
return reader::empty(read.start);
}
if read.kind == token_kind::block_end {
this._state = this.pop();
this._scanner.take();
return this.finish(event_kind::end_mapping, read.start);
}
return this.unexpected(&read);
}
def reader::block_mapping_value(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::value {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::key && next.kind != token_kind::value && next.kind != token_kind::block_end {
this._states.append(state::block_mapping_key);
return this.node(true, true);
}
this._state = state::block_mapping_key;
return reader::empty(read.end);
}
this._state = state::block_mapping_key;
return reader::empty(read.start);
}
def reader::flow_sequence_entry(&mut this, first: bool): maybe<event> {
if first {
this._scanner.take();
}
var read := this.peek() else { return nothing {}; };
if read.kind != token_kind::flow_sequence_end {
if !first {
if read.kind != token_kind::flow_entry {
return this.unexpected(&read);
}
this._scanner.take();
read = this.peek() else { return nothing {}; };
}
if read.kind == token_kind::key {
this._scanner.take();
this._state = state::flow_sequence_entry_mapping_key;
return this.begin(event_kind::begin_mapping, style::flow, strview::blank(), strview::blank(), read.start);
}
# An entry beginning with `:` is a pair whose key is empty.
if read.kind == token_kind::value {
this._state = state::flow_sequence_entry_mapping_key;
return this.begin(event_kind::begin_mapping, style::flow, strview::blank(), strview::blank(), read.start);
}
if read.kind != token_kind::flow_sequence_end {
this._states.append(state::flow_sequence_entry);
return this.node(false, false);
}
}
this._state = this.pop();
this._scanner.take();
return this.finish(event_kind::end_sequence, read.start);
}
def reader::flow_sequence_entry_mapping_key(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind != token_kind::value && read.kind != token_kind::flow_entry && read.kind != token_kind::flow_sequence_end {
this._states.append(state::flow_sequence_entry_mapping_value);
return this.node(false, false);
}
this._state = state::flow_sequence_entry_mapping_value;
return reader::empty(read.start);
}
def reader::flow_sequence_entry_mapping_value(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
if read.kind == token_kind::value {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::flow_entry && next.kind != token_kind::flow_sequence_end {
this._states.append(state::flow_sequence_entry_mapping_end);
return this.node(false, false);
}
this._state = state::flow_sequence_entry_mapping_end;
return reader::empty(read.end);
}
this._state = state::flow_sequence_entry_mapping_end;
return reader::empty(read.start);
}
def reader::flow_sequence_entry_mapping_end(&mut this): maybe<event> {
val read := this.peek() else { return nothing {}; };
this._state = state::flow_sequence_entry;
return this.finish(event_kind::end_mapping, read.start);
}
def reader::flow_mapping_key(&mut this, first: bool): maybe<event> {
if first {
this._scanner.take();
}
var read := this.peek() else { return nothing {}; };
if read.kind != token_kind::flow_mapping_end {
if !first {
if read.kind != token_kind::flow_entry {
return this.unexpected(&read);
}
this._scanner.take();
read = this.peek() else { return nothing {}; };
}
if read.kind == token_kind::key {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::value && next.kind != token_kind::flow_entry && next.kind != token_kind::flow_mapping_end {
this._states.append(state::flow_mapping_value);
return this.node(false, false);
}
this._state = state::flow_mapping_value;
return reader::empty(read.end);
}
# A member beginning with `:` has an empty key.
if read.kind == token_kind::value {
this._state = state::flow_mapping_value;
return reader::empty(read.start);
}
if read.kind != token_kind::flow_mapping_end {
this._states.append(state::flow_mapping_empty_value);
return this.node(false, false);
}
}
this._state = this.pop();
this._scanner.take();
return this.finish(event_kind::end_mapping, read.start);
}
def reader::flow_mapping_value(&mut this, empty: bool): maybe<event> {
val read := this.peek() else { return nothing {}; };
if empty {
this._state = state::flow_mapping_key;
return reader::empty(read.start);
}
if read.kind == token_kind::value {
this._scanner.take();
val next := this.peek() else { return nothing {}; };
if next.kind != token_kind::flow_entry && next.kind != token_kind::flow_mapping_end {
this._states.append(state::flow_mapping_key);
return this.node(false, false);
}
this._state = state::flow_mapping_key;
return reader::empty(read.end);
}
this._state = state::flow_mapping_key;
return reader::empty(read.start);
}