Initial Commit
This commit is contained in:
1624 files changed
+43408
No files matched your search
@@ -0,0 +1,56 @@
|
||||
# std::yaml
|
||||
|
||||
`std::yaml` reads and writes YAML for Sakura, as YAML 1.2.2 writes it, by its
|
||||
core schema: a plain scalar is empty, a boolean, an integer, a float, or text by
|
||||
how it is written, and a quoted or block scalar is always text. `yaml::parse`
|
||||
reads a stream of documents into a `yaml::document`, keeping each value's line,
|
||||
tag, and every key a mapping repeats; `yaml::reader` gives one event at a time,
|
||||
and `yaml::writer` writes YAML in block style as it is given it. A value whose
|
||||
type marks its fields with `@serial` is written as YAML and read back by those
|
||||
marks, over `std::serial`. Limits on depth and aliases stop text written to
|
||||
exhaust a reader.
|
||||
|
||||
## Using it
|
||||
|
||||
Require the standard library in your blossomfile, and name the module among a
|
||||
target's `deps`, with the other modules of std it reads:
|
||||
|
||||
```yaml
|
||||
requires:
|
||||
- https://git.malunal.studio/sakura/std@v1.0.0
|
||||
|
||||
targets:
|
||||
- name: app
|
||||
type: program
|
||||
deps: [std.yaml, std.io]
|
||||
```
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import std::yaml;
|
||||
|
||||
def main(): void {
|
||||
val read := yaml::parse("name: sakura\nstars: 5\n") else (_) {
|
||||
io::println("That isn't YAML.");
|
||||
return;
|
||||
};
|
||||
if read.root.get("name") is some(name) {
|
||||
if name.as_text() is value(text) {
|
||||
io::println(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
From the standard library's root, where the conformance test finds its suite,
|
||||
`blossom test --only std.yaml` runs them, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib std=. tests/main.sakura tests/yaml/*.sakura
|
||||
```
|
||||
|
||||
The conformance test reads the YAML test suite's cases, in `tests/yaml/suite`, under
|
||||
its MIT license. The tests compare what YAML's documents hold with the JSON the suite
|
||||
gives, so they read `std::json` too.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,721 @@
|
||||
#! @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);
|
||||
}
|
||||
+1409
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,620 @@
|
||||
#! @file text.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what YAML's text is made of: which characters it allows, what a plain
|
||||
#! scalar resolves to by the core schema, how numbers read, and how text is written
|
||||
#! back so that it reads as the same text.
|
||||
|
||||
module std::yaml;
|
||||
|
||||
|
||||
# The digits an escape is written with.
|
||||
const hex_digits: strview = "0123456789ABCDEF";
|
||||
|
||||
# What a plain scalar resolves to by the core schema.
|
||||
enum resolved: u8 {
|
||||
empty, #! `null`, `Null`, `NULL`, `~`, or nothing.
|
||||
truth, #! `true`, `True`, or `TRUE`.
|
||||
falsehood, #! `false`, `False`, or `FALSE`.
|
||||
integer, #! Decimal, `0o` octal, or `0x` hexadecimal.
|
||||
real, #! A float, `.inf`, or `.nan`.
|
||||
text, #! Anything else.
|
||||
}
|
||||
|
||||
# Whether a byte separates words on a line: a space or a tab.
|
||||
def is_blank(byte: u8): bool {
|
||||
return byte == ' ' || byte == '\t';
|
||||
}
|
||||
|
||||
# Whether a byte breaks a line.
|
||||
def is_break(byte: u8): bool {
|
||||
return byte == '\n' || byte == '\r';
|
||||
}
|
||||
|
||||
# Whether a byte ends what is written on a line: a blank, a break, or the end of the
|
||||
# text, which the scanner reads as 0, since the text holds no zero byte.
|
||||
def is_blankz(byte: u8): bool {
|
||||
return byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r' || byte == 0;
|
||||
}
|
||||
|
||||
# Whether a byte breaks a line or is the end of the text.
|
||||
def is_breakz(byte: u8): bool {
|
||||
return byte == '\n' || byte == '\r' || byte == 0;
|
||||
}
|
||||
|
||||
# Whether a byte begins or ends a flow collection, or separates its entries.
|
||||
def is_flow_indicator(byte: u8): bool {
|
||||
return byte == ',' || byte == '[' || byte == ']' || byte == '{' || byte == '}';
|
||||
}
|
||||
|
||||
# Whether a byte may be in a tag handle's name: a letter, a digit, or `-`.
|
||||
def is_word(byte: u8): bool {
|
||||
return byte.is_alnum || byte == '-';
|
||||
}
|
||||
|
||||
# Whether a byte may be written in a URI, as a tag is, other than in a `%` escape.
|
||||
def is_uri_char(byte: u8): bool {
|
||||
if byte.is_alnum {
|
||||
return true;
|
||||
}
|
||||
return match byte {
|
||||
'-', '#', ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '_', '.', '!', '~', '*', '\'',
|
||||
'(', ')', '[', ']' => true,
|
||||
else => false,
|
||||
};
|
||||
}
|
||||
|
||||
# Whether a byte may be written in a tag's suffix: what a URI holds, but `!` and the
|
||||
# flow indicators.
|
||||
def is_tag_char(byte: u8): bool {
|
||||
return is_uri_char(byte) && byte != '!' && !is_flow_indicator(byte);
|
||||
}
|
||||
|
||||
# Finds the first byte of the text YAML does not allow, where text must be UTF-8 and
|
||||
# only of printable characters: no control characters but the tab and line breaks, no
|
||||
# DEL, no C1 control characters but NEL, and neither U+FFFE nor U+FFFF.
|
||||
def first_disallowed(text: strview): maybe<disallowed> {
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte >= 0x20 && byte < 0x7F {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
if byte < 0x80 {
|
||||
if (byte < 0x20 && byte != '\t' && byte != '\n' && byte != '\r') || byte == 0x7F {
|
||||
# A zero byte at the start is UTF-16 or UTF-32, which YAML could be, but this
|
||||
# does not read.
|
||||
val kind := byte == 0 && at < 4 ? error_kind::invalid_utf8 : error_kind::invalid_character;
|
||||
return disallowed { kind = kind, offset = at };
|
||||
}
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
val count := serial::utf8_length(text, at);
|
||||
if count == 0 {
|
||||
return disallowed { kind = error_kind::invalid_utf8, offset = at };
|
||||
}
|
||||
if count == 2 && byte == 0xC2 && text[at + 1] < 0xA0 && text[at + 1] != 0x85 {
|
||||
return disallowed { kind = error_kind::invalid_character, offset = at };
|
||||
}
|
||||
if count == 3 && byte == 0xEF && text[at + 1] == 0xBF && text[at + 2] >= 0xBE {
|
||||
return disallowed { kind = error_kind::invalid_character, offset = at };
|
||||
}
|
||||
at += count;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# A byte the text holds that YAML does not allow, and why.
|
||||
struct disallowed {
|
||||
var kind: error_kind;
|
||||
var offset: u64;
|
||||
}
|
||||
|
||||
# What a plain scalar's text resolves to, by the core schema.
|
||||
def resolve(text: strview): resolved {
|
||||
if text.length == 0 {
|
||||
return resolved::empty;
|
||||
}
|
||||
|
||||
# Only text beginning with one of these resolves to anything but text, so most
|
||||
# resolves in one comparison.
|
||||
val first := text[0];
|
||||
if !first.is_digit && first != '-' && first != '+' && first != '.' && first != '~'
|
||||
&& first != 'n' && first != 'N' && first != 't' && first != 'T' && first != 'f' && first != 'F' {
|
||||
return resolved::text;
|
||||
}
|
||||
|
||||
if first == '~' || first == 'n' || first == 'N' {
|
||||
return text == "~" || text == "null" || text == "Null" || text == "NULL" ? resolved::empty : resolved::text;
|
||||
}
|
||||
if first == 't' || first == 'T' {
|
||||
return text == "true" || text == "True" || text == "TRUE" ? resolved::truth : resolved::text;
|
||||
}
|
||||
if first == 'f' || first == 'F' {
|
||||
return text == "false" || text == "False" || text == "FALSE" ? resolved::falsehood : resolved::text;
|
||||
}
|
||||
if is_integer(text) {
|
||||
return resolved::integer;
|
||||
}
|
||||
if is_real(text) {
|
||||
return resolved::real;
|
||||
}
|
||||
return resolved::text;
|
||||
}
|
||||
|
||||
# Whether text is an integer by the core schema: `[-+]?[0-9]+`, `0o[0-7]+`, or
|
||||
# `0x[0-9a-fA-F]+`.
|
||||
def is_integer(text: strview): bool {
|
||||
if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') {
|
||||
val hex := text[1] == 'x';
|
||||
for at in 2..text.length {
|
||||
val byte := text[at];
|
||||
if hex ? !byte.is_hex : !byte.is_oct {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0;
|
||||
if at == text.length {
|
||||
return false;
|
||||
}
|
||||
while at < text.length {
|
||||
if !text[at].is_digit {
|
||||
return false;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether text is a float by the core schema:
|
||||
# `[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?`, `[-+]?\.inf` and `\.nan`
|
||||
# in their three cases.
|
||||
def is_real(text: strview): bool {
|
||||
var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0;
|
||||
val rest := text.substr(at, text.length);
|
||||
if rest == ".inf" || rest == ".Inf" || rest == ".INF" {
|
||||
return true;
|
||||
}
|
||||
if at == 0 && (rest == ".nan" || rest == ".NaN" || rest == ".NAN") {
|
||||
return true;
|
||||
}
|
||||
|
||||
var digits: u64 = 0;
|
||||
while at < text.length && text[at].is_digit {
|
||||
at++;
|
||||
digits++;
|
||||
}
|
||||
if at < text.length && text[at] == '.' {
|
||||
at++;
|
||||
while at < text.length && text[at].is_digit {
|
||||
at++;
|
||||
digits++;
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
if at < text.length && (text[at] == 'e' || text[at] == 'E') {
|
||||
at++;
|
||||
if at < text.length && (text[at] == '-' || text[at] == '+') {
|
||||
at++;
|
||||
}
|
||||
val exponent := at;
|
||||
while at < text.length && text[at].is_digit {
|
||||
at++;
|
||||
}
|
||||
if at == exponent {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return at == text.length;
|
||||
}
|
||||
|
||||
# A number's text as an integer exactly, in any base the core schema has: whether it
|
||||
# is whole, and fits in 64 bits. A float that is a whole number, as `1e3` is, is one.
|
||||
def integral_of(text: strview): serial::integral {
|
||||
if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') {
|
||||
val base: u64 = text[1] == 'x' ? 16 : 8;
|
||||
var made := serial::integral { whole = true, fits = true };
|
||||
for at in 2..text.length {
|
||||
val digit := text[at].digit_value;
|
||||
if made.magnitude > (0xFFFFFFFFFFFFFFFFu - digit) / base {
|
||||
made.fits = false;
|
||||
return made;
|
||||
}
|
||||
made.magnitude = made.magnitude * base + digit;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
# Infinity and NaN are no integer.
|
||||
val last := text[text.length - 1];
|
||||
if !last.is_digit && last != '.' {
|
||||
return serial::integral {};
|
||||
}
|
||||
return serial::integral_of(text);
|
||||
}
|
||||
|
||||
# A number's text as the nearest 64-bit float, or `nothing` where it is too large.
|
||||
def real_of(text: strview): maybe<f64> {
|
||||
var at: u64 = text[0] == '-' || text[0] == '+' ? 1 : 0;
|
||||
val negative := text[0] == '-';
|
||||
val rest := text.substr(at, text.length);
|
||||
if rest == ".inf" || rest == ".Inf" || rest == ".INF" {
|
||||
return negative ? -1.0 / 0.0 : 1.0 / 0.0;
|
||||
}
|
||||
if rest == ".nan" || rest == ".NaN" || rest == ".NAN" {
|
||||
return 0.0 / 0.0;
|
||||
}
|
||||
|
||||
if text.length > 2 && text[0] == '0' && (text[1] == 'o' || text[1] == 'x') {
|
||||
val read := integral_of(text);
|
||||
if !read.fits {
|
||||
val base: f64 = text[1] == 'x' ? 16.0 : 8.0;
|
||||
var made: f64 = 0.0;
|
||||
for index in 2..text.length {
|
||||
made = made * base + text[index].digit_value as f64;
|
||||
}
|
||||
return made;
|
||||
}
|
||||
return read.magnitude as f64;
|
||||
}
|
||||
|
||||
match real::parse::<f64>(text) {
|
||||
value(read) => return read;
|
||||
error(&_) => return nothing {};
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# Whether text written plain reads back as the same text, as a value, or as a key,
|
||||
# which is also on one line. Decision 7 has it quote, too, what YAML 1.1 reads as
|
||||
# another kind, so readers of either version read the same.
|
||||
def plain_writes(text: strview): bool {
|
||||
if text.length == 0 || resolve(text) != resolved::text || reads_otherwise_in_1_1(text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
# It begins with no indicator, but `-`, `?`, or `:` before what is plain, and holds
|
||||
# no space at either end.
|
||||
val first := text[0];
|
||||
val second: u8 = text.length > 1 ? text[1] : 0;
|
||||
match first {
|
||||
',', '[', ']', '{', '}', '#', '&', '*', '!', '|', '>', '\'', '"', '%', '@', '`', ' ', '\t' => return false;
|
||||
'-', '?', ':' => {
|
||||
if is_blankz(second) || is_flow_indicator(second) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else => {}
|
||||
}
|
||||
val last := text[text.length - 1];
|
||||
if last == ' ' || last == '\t' || last == ':' {
|
||||
return false;
|
||||
}
|
||||
|
||||
# Nothing within it ends it, or begins a comment, and each character is printable,
|
||||
# with no line break, and none of the flow indicators, so it reads the same within
|
||||
# a flow collection too.
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte < 0x20 || byte == 0x7F || is_flow_indicator(byte) {
|
||||
return false;
|
||||
}
|
||||
if byte == ':' && at + 1 < text.length && (text[at + 1] == ' ' || text[at + 1] == '\t') {
|
||||
return false;
|
||||
}
|
||||
if byte == '#' && at > 0 && (text[at - 1] == ' ' || text[at - 1] == '\t') {
|
||||
return false;
|
||||
}
|
||||
if byte >= 0x80 {
|
||||
val count := serial::utf8_length(text, at);
|
||||
if count == 0 || !printable_at(text, at) {
|
||||
return false;
|
||||
}
|
||||
at += count;
|
||||
continue;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
|
||||
# A document marker would end the document.
|
||||
if text.starts_with("---") || text.starts_with("...") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether YAML 1.1 reads plain text as something else, as PyYAML's resolver and the
|
||||
# 1.1 spec do: its booleans, numbers with `_` or in base 2 or 60, dates, the merge
|
||||
# key, and `=`.
|
||||
def reads_otherwise_in_1_1(text: strview): bool {
|
||||
if text.length <= 5 {
|
||||
val lower := text.lower();
|
||||
val word := lower.span;
|
||||
if word == "y" || word == "n" || word == "yes" || word == "no" || word == "on" || word == "off" {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if text == "<<" || text == "=" {
|
||||
return true;
|
||||
}
|
||||
return is_1_1_integer(text) || is_1_1_float(text) || is_1_1_date(text);
|
||||
}
|
||||
|
||||
# Whether text is a YAML 1.1 integer: `0b` binary, `0` octal, `0x` hexadecimal, or
|
||||
# decimal, each with `_` among the digits, or sexagesimal, as `1:30`.
|
||||
def is_1_1_integer(text: strview): bool {
|
||||
var at: u64 = text.length > 0 && (text[0] == '-' || text[0] == '+') ? 1 : 0;
|
||||
val rest := text.substr(at, text.length);
|
||||
if rest.length > 2 && rest[0] == '0' && (rest[1] == 'b' || rest[1] == 'x') {
|
||||
val hex := rest[1] == 'x';
|
||||
for index in 2..rest.length {
|
||||
val byte := rest[index];
|
||||
if byte != '_' && !(hex ? byte.is_hex : (byte == '0' || byte == '1')) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
val digits := digits_end(rest, 0);
|
||||
if digits == 0 {
|
||||
return false;
|
||||
}
|
||||
if digits == rest.length {
|
||||
return true;
|
||||
}
|
||||
return rest[0] != '0' && sexagesimal_end(rest, digits) == rest.length;
|
||||
}
|
||||
|
||||
# Whether text is a YAML 1.1 float: digits with `_`, a `.`, and an exponent, or a
|
||||
# sexagesimal one, as `1:30.5`.
|
||||
def is_1_1_float(text: strview): bool {
|
||||
var at: u64 = text.length > 0 && (text[0] == '-' || text[0] == '+') ? 1 : 0;
|
||||
val rest := text.substr(at, text.length);
|
||||
var index := digits_end(rest, 0);
|
||||
if index > 0 && index < rest.length && rest[index] == ':' {
|
||||
index = sexagesimal_end(rest, index);
|
||||
}
|
||||
if index >= rest.length || rest[index] != '.' {
|
||||
return false;
|
||||
}
|
||||
val whole := index;
|
||||
index = digits_end(rest, index + 1);
|
||||
if whole == 0 && index == 1 {
|
||||
return false;
|
||||
}
|
||||
if index < rest.length && (rest[index] == 'e' || rest[index] == 'E') {
|
||||
index++;
|
||||
if index >= rest.length || (rest[index] != '-' && rest[index] != '+') {
|
||||
return false;
|
||||
}
|
||||
val exponent := index + 1;
|
||||
index = exponent;
|
||||
while index < rest.length && rest[index].is_digit {
|
||||
index++;
|
||||
}
|
||||
if index == exponent {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return index == rest.length;
|
||||
}
|
||||
|
||||
# Whether text is a YAML 1.1 date, `2026-10-06`, or a time stamp beginning with one.
|
||||
def is_1_1_date(text: strview): bool {
|
||||
if text.length < 8 || !text[0].is_digit || !text[1].is_digit || !text[2].is_digit || !text[3].is_digit || text[4] != '-' {
|
||||
return false;
|
||||
}
|
||||
var index: u64 = 5;
|
||||
for _ in 0..2 {
|
||||
val first := index;
|
||||
while index < text.length && index < first + 2 && text[index].is_digit {
|
||||
index++;
|
||||
}
|
||||
if index == first {
|
||||
return false;
|
||||
}
|
||||
if index < text.length && text[index] == '-' && first == 5 {
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return index == text.length || text[index] == 'T' || text[index] == 't' || text[index] == ' ' || text[index] == '\t';
|
||||
}
|
||||
|
||||
# Where a run of decimal digits, and `_` among them, ends.
|
||||
def digits_end(text: strview, from: u64): u64 {
|
||||
var index := from;
|
||||
while index < text.length && (text[index].is_digit || (index > from && text[index] == '_')) {
|
||||
index++;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
# Where sexagesimal parts, each `:` and one or two digits, end, from a `:`.
|
||||
def sexagesimal_end(text: strview, from: u64): u64 {
|
||||
var index := from;
|
||||
while index < text.length && text[index] == ':' {
|
||||
val first := index + 1;
|
||||
index = first;
|
||||
while index < text.length && index < first + 2 && text[index].is_digit {
|
||||
index++;
|
||||
}
|
||||
if index == first {
|
||||
return first - 1;
|
||||
}
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
# Whether the character beginning at a byte is printable: not a C1 control character,
|
||||
# nor U+FFFE or U+FFFF, nor anything YAML writes only escaped.
|
||||
def printable_at(text: strview, at: u64): bool {
|
||||
val byte := text[at];
|
||||
if byte == 0xC2 && text[at + 1] < 0xA0 {
|
||||
return false;
|
||||
}
|
||||
if byte == 0xEF && text[at + 1] == 0xBB && text[at + 2] == 0xBF {
|
||||
return false;
|
||||
}
|
||||
if byte == 0xEF && text[at + 1] == 0xBF && text[at + 2] >= 0xBE {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
# Whether text reads back the same written as a literal block: it holds a line break,
|
||||
# is printable, has no carriage return, and has no line of only spaces or tabs, which
|
||||
# a block would read as empty, nor a tab after a line break, which a block would read
|
||||
# as indentation.
|
||||
def literal_writes(text: strview): bool {
|
||||
var breaks: u64 = 0;
|
||||
var line_blank := true;
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte == '\n' {
|
||||
if line_blank && at > 0 && text[at - 1] != '\n' {
|
||||
return false;
|
||||
}
|
||||
breaks++;
|
||||
line_blank = true;
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
if byte == '\t' && (at == 0 || text[at - 1] == '\n') {
|
||||
return false;
|
||||
}
|
||||
if (byte < 0x20 && byte != '\t') || byte == 0x7F {
|
||||
return false;
|
||||
}
|
||||
if byte >= 0x80 {
|
||||
val count := serial::utf8_length(text, at);
|
||||
if count == 0 || !printable_at(text, at) {
|
||||
return false;
|
||||
}
|
||||
line_blank = false;
|
||||
at += count;
|
||||
continue;
|
||||
}
|
||||
if byte != ' ' && byte != '\t' {
|
||||
line_blank = false;
|
||||
}
|
||||
at++;
|
||||
}
|
||||
if line_blank && text.length > 0 && text[text.length - 1] != '\n' {
|
||||
return false;
|
||||
}
|
||||
return breaks > 0;
|
||||
}
|
||||
|
||||
# Appends text double-quoted, with YAML's escapes for what is not printable.
|
||||
# @returns Whether the text is UTF-8: text that is not is appended only as far as its
|
||||
# first byte that breaks UTF-8, without the closing quote.
|
||||
def append_double(text: strview, into: &mut string): bool {
|
||||
into.push('"');
|
||||
var run: u64 = 0;
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte >= 0x80 {
|
||||
val count := serial::utf8_length(text, at);
|
||||
if count == 0 {
|
||||
into.append(text.substr(run, at - run));
|
||||
return false;
|
||||
}
|
||||
if printable_at(text, at) {
|
||||
at += count;
|
||||
continue;
|
||||
}
|
||||
|
||||
into.append(text.substr(run, at - run));
|
||||
append_code_escape(code_at(text, at, count), into);
|
||||
at += count;
|
||||
run = at;
|
||||
continue;
|
||||
}
|
||||
if byte >= 0x20 && byte != 0x7F && byte != '"' && byte != '\\' {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
into.append(text.substr(run, at - run));
|
||||
into.push('\\');
|
||||
match byte {
|
||||
'"' => into.push('"');
|
||||
'\\' => into.push('\\');
|
||||
'\n' => into.push('n');
|
||||
'\r' => into.push('r');
|
||||
'\t' => into.push('t');
|
||||
0x00 => into.push('0');
|
||||
0x07 => into.push('a');
|
||||
0x08 => into.push('b');
|
||||
0x0B => into.push('v');
|
||||
0x0C => into.push('f');
|
||||
0x1B => into.push('e');
|
||||
else => {
|
||||
into.push('x');
|
||||
into.push(hex_digits[(byte >> 4) as u64]);
|
||||
into.push(hex_digits[(byte & 0x0F) as u64]);
|
||||
}
|
||||
}
|
||||
at++;
|
||||
run = at;
|
||||
}
|
||||
into.append(text.substr(run, at - run));
|
||||
into.push('"');
|
||||
return true;
|
||||
}
|
||||
|
||||
# The character a UTF-8 sequence of a length writes.
|
||||
def code_at(text: strview, at: u64, count: u64): u64 {
|
||||
val lead := text[at] as u64;
|
||||
var code: u64 = count == 2 ? lead & 0x1F : (count == 3 ? lead & 0x0F : lead & 0x07);
|
||||
for index in 1..count {
|
||||
code = (code << 6) | ((text[at + index] as u64) & 0x3F);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
# Appends the escape of a character not written as it is, as `\u0085`, or `\N`,
|
||||
# `\_`, `\L`, and `\P` for the ones YAML names.
|
||||
def append_code_escape(code: u64, into: &mut string): void {
|
||||
if code == 0x85 {
|
||||
into.append("\\N");
|
||||
return;
|
||||
}
|
||||
if code == 0xA0 {
|
||||
into.append("\\_");
|
||||
return;
|
||||
}
|
||||
if code == 0x2028 {
|
||||
into.append("\\L");
|
||||
return;
|
||||
}
|
||||
if code == 0x2029 {
|
||||
into.append("\\P");
|
||||
return;
|
||||
}
|
||||
|
||||
val wide := code > 0xFFFF;
|
||||
into.append(wide ? "\\U" : "\\u");
|
||||
var shift: u64 = wide ? 28 : 12;
|
||||
while true {
|
||||
into.push(hex_digits[(code >> shift) & 0xF]);
|
||||
if shift == 0 {
|
||||
break;
|
||||
}
|
||||
shift -= 4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
#! @file writer.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the writer, which writes YAML in block style as it is given it, without
|
||||
#! building a tree first.
|
||||
|
||||
import std::io;
|
||||
module std::yaml;
|
||||
|
||||
|
||||
# How much text a writer passing its text on holds before it does.
|
||||
const pass_bytes: u64 = 16384;
|
||||
|
||||
# The longest key written plain or quoted on its line, past which it is written after
|
||||
# `?`, as YAML limits implicit keys.
|
||||
const key_limit: u64 = 1024;
|
||||
|
||||
# What the next value follows.
|
||||
const after_nothing: u8 = 0; # It begins a document.
|
||||
const after_key: u8 = 1; # A key's `:`, after which it is on the same line or begins below.
|
||||
const after_dash: u8 = 2; # A sequence's `-`, after which it begins on the same line.
|
||||
|
||||
# Each open mapping or sequence of a writer.
|
||||
struct level {
|
||||
var mapping: bool;
|
||||
var column: u64; #! Where its entries begin.
|
||||
var count: u64; #! How many entries are begun.
|
||||
var after: u8; #! What it follows.
|
||||
var named: bool; #! Whether a mapping's key is written, and its value is next.
|
||||
}
|
||||
|
||||
#! Writes YAML in block style into a string it owns, as it is given it:
|
||||
#! indentation, dashes, colons, quotes, and block scalars are its own.
|
||||
#!
|
||||
#! Text is written plain where it reads back as the same text, as a literal
|
||||
#! block where it holds line breaks, and double-quoted with escapes otherwise.
|
||||
#! Each level of nesting is indented by two spaces, or as many as `writer::new`
|
||||
#! is given, with a sequence indented under its key, and an empty collection
|
||||
#! written `{}` or `[]`.
|
||||
#!
|
||||
#! A writer made by `writer::to` passes its text on to a stream instead,
|
||||
#! whenever it holds 16 KB and when it finishes. It borrows the stream, which
|
||||
#! the caller flushes and closes.
|
||||
#!
|
||||
#! Misuse stops the program, as indexing past an array does: a member outside a
|
||||
#! mapping, a value within a mapping without its key, ending a sequence where a
|
||||
#! mapping is open, a second value in a document, or finishing with something
|
||||
#! still open. Text that is not UTF-8 is written as `null` in its place, and
|
||||
#! `finish` gives `invalid_utf8`.
|
||||
#!
|
||||
#! The writer is a `serial::encoder`, so `yaml::encode` and `serial::encode`
|
||||
#! write typed values through it, among what it is given by hand.
|
||||
pub struct writer : serial::encoder, moveable {
|
||||
pub var _text: string; #! The text written so far, which std's tests read.
|
||||
var _indent: u64; #! Spaces for each level of nesting.
|
||||
var _levels: vector<level>;
|
||||
var _pending: u8; #! What the next value follows.
|
||||
var _written: bool; #! Whether the document's value is begun, after which there is no other.
|
||||
var _failure: maybe<error_kind>;
|
||||
var _out: maybe<&mut writable>; #! Where the text is passed on, for a writer `to` makes.
|
||||
var _pass_at: u64; #! How much text is held before it is passed on, or 0 for never.
|
||||
}
|
||||
|
||||
#! Makes a writer.
|
||||
#! @param indent Spaces for each level of nesting, from 1 to 9.
|
||||
#! @param alloc An optional allocator for the writer to take memory from.
|
||||
#! @returns The writer, which holds no text yet.
|
||||
pub def writer::new(indent: u32 = 2, alloc: maybe<&mut allocator> = nothing {}): writer {
|
||||
expects(indent >= 1 && indent <= 9, "A writer indents each level by 1 to 9 spaces.");
|
||||
return writer { _text = string::new(alloc), _indent = indent as u64, _levels = vector::<level>::new(alloc) };
|
||||
}
|
||||
|
||||
#! Makes a writer that passes what it writes on to a stream, whenever it holds
|
||||
#! 16 KB and when it finishes, rather than holding it all.
|
||||
#! @param out The stream to write to, which the writer borrows, and which
|
||||
#! whoever made it flushes and closes.
|
||||
#! @param indent Spaces for each level of nesting, from 1 to 9.
|
||||
#! @param alloc An optional allocator for the writer to take memory from.
|
||||
#! @returns The writer.
|
||||
pub def writer::to(out: &mut writable, indent: u32 = 2, alloc: maybe<&mut allocator> = nothing {}): writer {
|
||||
expects(indent >= 1 && indent <= 9, "A writer indents each level by 1 to 9 spaces.");
|
||||
return writer {
|
||||
_text = string::new(alloc),
|
||||
_indent = indent as u64,
|
||||
_levels = vector::<level>::new(alloc),
|
||||
_out = out,
|
||||
_pass_at = pass_bytes
|
||||
};
|
||||
}
|
||||
|
||||
#! Creates a writer by taking another's text and what it has open, which leaves
|
||||
#! the other holding nothing.
|
||||
#! @param other The writer to move from.
|
||||
#! @returns The writer.
|
||||
pub def writer::move_of(other: &mut writer): writer {
|
||||
val made := writer {
|
||||
_text = move(other._text),
|
||||
_indent = other._indent,
|
||||
_levels = move(other._levels),
|
||||
_pending = other._pending,
|
||||
_written = other._written,
|
||||
_failure = other._failure,
|
||||
_out = other._out,
|
||||
_pass_at = other._pass_at
|
||||
};
|
||||
other._written = false;
|
||||
other._failure = nothing {};
|
||||
other._out = nothing {};
|
||||
other._pass_at = 0;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! Gives the text written, once each document's value is written whole. A writer
|
||||
#! `to` a stream passes on what it still holds, and gives an empty view.
|
||||
#! @param this The writer to finish.
|
||||
#! @returns A view of the text, good until the writer is written to, cleared, or
|
||||
#! closed, or the first failure, which has no place, or `not_written`
|
||||
#! where the stream failed.
|
||||
pub def writer::finish(&mut this): result<strview, error> {
|
||||
expects(this._written && this._levels.length == 0,
|
||||
"A writer finishes once its value is written whole, with nothing left open.");
|
||||
if this._pass_at != 0 {
|
||||
this.pass();
|
||||
}
|
||||
if this._failure is some(kind) {
|
||||
return error { kind = kind };
|
||||
}
|
||||
return this._text.span;
|
||||
}
|
||||
|
||||
#! Ends the document written, and begins another after a `---` line.
|
||||
#! @param this The writer to write with, whose document's value is written
|
||||
#! whole.
|
||||
pub def writer::document(&mut this): void {
|
||||
expects(this._written && this._levels.length == 0,
|
||||
"A document ends once its value is written whole, with nothing left open.");
|
||||
this._text.append("---\n");
|
||||
this._written = false;
|
||||
}
|
||||
|
||||
#! Empties the writer to write another stream, keeping its memory.
|
||||
#! @param this The writer to empty.
|
||||
pub def writer::clear(&mut this): void {
|
||||
this._text.clear();
|
||||
this._levels.clear();
|
||||
this._pending = after_nothing;
|
||||
this._written = false;
|
||||
this._failure = nothing {};
|
||||
}
|
||||
|
||||
#! Begins a mapping, whose members are each written as `member` and a value.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::begin_object(&mut this): void {
|
||||
this.open(true);
|
||||
}
|
||||
|
||||
#! Begins a mapping, as `serial::encode` does, knowing how many members it
|
||||
#! holds.
|
||||
#! @param this The writer to write with.
|
||||
#! @param count How many members the mapping holds, which YAML need not know.
|
||||
pub def writer::begin_object(&mut this, count: u64): void {
|
||||
this.open(true);
|
||||
}
|
||||
|
||||
#! Writes the key of the member whose value is written next.
|
||||
#! @param this The writer to write with, within a mapping.
|
||||
#! @param name The key's text, which is quoted where it would read as
|
||||
#! something else.
|
||||
pub def writer::member(&mut this, name: strview): void {
|
||||
expects(this._levels.length > 0 && this.top().mapping, "A member is written only within a mapping.");
|
||||
expects(!this.top().named, "A member's value is written before the next member.");
|
||||
|
||||
this.entry();
|
||||
val start := this._text.length;
|
||||
if !this.append_key(name) {
|
||||
this._text.resize(start);
|
||||
this._text.append("null");
|
||||
this.keep(error_kind::invalid_utf8);
|
||||
}
|
||||
|
||||
# A key too long to be implicit is written after `?`, with its `:` on a line below.
|
||||
if this._text.length - start > key_limit {
|
||||
val key := string::from(this._text.span.substr(start, this._text.length - start), nothing {});
|
||||
this._text.resize(start);
|
||||
this._text.append("? ");
|
||||
this._text.append(key.span);
|
||||
this._text.push('\n');
|
||||
this.spaces(this.top().column);
|
||||
}
|
||||
this._text.push(':');
|
||||
this.top().named = true;
|
||||
this._pending = after_key;
|
||||
}
|
||||
|
||||
#! Ends the innermost mapping.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::end_object(&mut this): void {
|
||||
expects(this._levels.length > 0 && this.top().mapping, "A mapping is ended only where one is open innermost.");
|
||||
expects(!this.top().named, "A member's value is written before the mapping ends.");
|
||||
this.close("{}");
|
||||
}
|
||||
|
||||
#! Begins a sequence.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::begin_array(&mut this): void {
|
||||
this.open(false);
|
||||
}
|
||||
|
||||
#! Begins a sequence, as `serial::encode` does, knowing how many elements it
|
||||
#! holds.
|
||||
#! @param this The writer to write with.
|
||||
#! @param count How many elements the sequence holds, which YAML need not
|
||||
#! know.
|
||||
pub def writer::begin_array(&mut this, count: u64): void {
|
||||
this.open(false);
|
||||
}
|
||||
|
||||
#! Ends the innermost sequence.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::end_array(&mut this): void {
|
||||
expects(this._levels.length > 0 && !this.top().mapping, "A sequence is ended only where one is open innermost.");
|
||||
this.close("[]");
|
||||
}
|
||||
|
||||
#! Writes text: plain where it reads back as the same text, as a literal block
|
||||
#! where it holds line breaks, and double-quoted otherwise.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The text, which must be UTF-8.
|
||||
pub def writer::text(&mut this, value: strview): void {
|
||||
this.before_value();
|
||||
if plain_writes(value) {
|
||||
this.scalar(value);
|
||||
return;
|
||||
}
|
||||
if literal_writes(value) && this.literal(value) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lead();
|
||||
val start := this._text.length;
|
||||
if !append_double(value, &mut this._text) {
|
||||
this._text.resize(start);
|
||||
this._text.append("null");
|
||||
this.keep(error_kind::invalid_utf8);
|
||||
}
|
||||
this._text.push('\n');
|
||||
this._pending = after_nothing;
|
||||
}
|
||||
|
||||
#! Writes a signed integer.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The integer.
|
||||
pub def writer::signed(&mut this, value: i64): void {
|
||||
this.before_value();
|
||||
this.scalar($"{value}".span);
|
||||
}
|
||||
|
||||
#! Writes an unsigned integer.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The integer.
|
||||
pub def writer::unsigned(&mut this, value: u64): void {
|
||||
this.before_value();
|
||||
this.scalar($"{value}".span);
|
||||
}
|
||||
|
||||
#! Writes a float, as the shortest text that reads back as it, and infinity and
|
||||
#! NaN as `.inf`, `-.inf`, and `.nan`.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The float.
|
||||
pub def writer::real(&mut this, value: f64): void {
|
||||
this.before_value();
|
||||
if value != value {
|
||||
this.scalar(".nan");
|
||||
return;
|
||||
}
|
||||
if value - value != 0.0 {
|
||||
this.scalar(value > 0.0 ? ".inf" : "-.inf");
|
||||
return;
|
||||
}
|
||||
|
||||
# A whole float is written so it reads back as a float.
|
||||
val written := $"{value}";
|
||||
if is_integer(written.span) {
|
||||
this.scalar($"{written}.0".span);
|
||||
return;
|
||||
}
|
||||
this.scalar(written.span);
|
||||
}
|
||||
|
||||
#! Writes `true` or `false`.
|
||||
#! @param this The writer to write with.
|
||||
#! @param value The truth to write.
|
||||
pub def writer::boolean(&mut this, value: bool): void {
|
||||
this.before_value();
|
||||
this.scalar(value ? "true" : "false");
|
||||
}
|
||||
|
||||
#! Writes `null`.
|
||||
#! @param this The writer to write with.
|
||||
pub def writer::empty(&mut this): void {
|
||||
this.before_value();
|
||||
this.scalar("null");
|
||||
}
|
||||
|
||||
#! Keeps a failure `serial::encode` finds, as the writer keeps its own, to give
|
||||
#! it when it finishes.
|
||||
#! @param this The writer to keep it.
|
||||
#! @param kind The failure.
|
||||
pub def writer::fail(&mut this, kind: serial::error_kind): void {
|
||||
this.keep(of_serial(kind));
|
||||
}
|
||||
|
||||
# Begins a mapping or sequence, as a value. Nothing is written until its first entry
|
||||
# is, since an empty one is written `{}` or `[]` where it stands.
|
||||
def writer::open(&mut this, mapping: bool): void {
|
||||
this.before_value();
|
||||
var column: u64 = 0;
|
||||
if this._levels.length > 0 {
|
||||
column = this.top().column + this._indent;
|
||||
}
|
||||
this._levels.append(level { mapping = mapping, column = column, after = this._pending });
|
||||
this._pending = after_nothing;
|
||||
}
|
||||
|
||||
# Ends the innermost mapping or sequence, writing it `{}` or `[]` where it is empty.
|
||||
def writer::close(&mut this, empty: strview): void {
|
||||
this.passes();
|
||||
val ended: level = this.top();
|
||||
this._levels.remove_at(this._levels.length - 1);
|
||||
if ended.count > 0 {
|
||||
return;
|
||||
}
|
||||
if ended.after != after_nothing {
|
||||
this._text.push(' ');
|
||||
}
|
||||
this._text.append(empty);
|
||||
this._text.push('\n');
|
||||
}
|
||||
|
||||
# Readies a value: within a sequence, after its `-`, and within a mapping, after its
|
||||
# member's key.
|
||||
def writer::before_value(&mut this): void {
|
||||
this.passes();
|
||||
if this._levels.length == 0 {
|
||||
expects(!this._written, "A writer writes one value a document; a sequence holds more than one.");
|
||||
this._written = true;
|
||||
return;
|
||||
}
|
||||
|
||||
val top := &mut this.top();
|
||||
if top.mapping {
|
||||
expects(top.named, "A value within a mapping follows its member's key.");
|
||||
top.named = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.entry();
|
||||
this._text.push('-');
|
||||
this._pending = after_dash;
|
||||
}
|
||||
|
||||
# Begins an entry of the innermost collection: on the line its key or `-` is on, for
|
||||
# its first entry, and on a line of its own, indented, for any other.
|
||||
def writer::entry(&mut this): void {
|
||||
val top := &mut this.top();
|
||||
if top.count == 0 {
|
||||
if top.after == after_key {
|
||||
this._text.push('\n');
|
||||
this.spaces(top.column);
|
||||
} else if top.after == after_dash {
|
||||
this.spaces(this._indent - 1);
|
||||
}
|
||||
} else {
|
||||
this.spaces(top.column);
|
||||
}
|
||||
top.count++;
|
||||
}
|
||||
|
||||
# Writes what comes before a value on the line its key or `-` is on.
|
||||
def writer::lead(&mut this): void {
|
||||
if this._pending != after_nothing {
|
||||
this._text.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
# Writes a scalar as it is, ending its line.
|
||||
def writer::scalar(&mut this, written: strview): void {
|
||||
this.lead();
|
||||
this._text.append(written);
|
||||
this._text.push('\n');
|
||||
this._pending = after_nothing;
|
||||
}
|
||||
|
||||
# Writes text as a literal block, its lines indented past what holds it, with the
|
||||
# indicators its first line and its final line breaks need, or gives `false` where it
|
||||
# cannot be, as text holding nothing but line breaks cannot.
|
||||
def writer::literal(&mut this, value: strview): bool {
|
||||
var trailing: u64 = 0;
|
||||
while trailing < value.length && value[value.length - 1 - trailing] == '\n' {
|
||||
trailing++;
|
||||
}
|
||||
val body := value.substr(0, value.length - trailing);
|
||||
if body.length == 0 {
|
||||
return false;
|
||||
}
|
||||
|
||||
# Where the lines begin, and where what holds the scalar is, as an indentation
|
||||
# indicator counts from it.
|
||||
var parent: i64 = -1;
|
||||
if this._levels.length > 0 {
|
||||
parent = this.top().column as i64;
|
||||
}
|
||||
val column := (parent + this._indent as i64) as u64;
|
||||
|
||||
# The first line holding anything begins with a space, so the indentation is
|
||||
# written, since it could not be found from that line.
|
||||
var first: u64 = 0;
|
||||
while first < body.length && body[first] == '\n' {
|
||||
first++;
|
||||
}
|
||||
val indicated := body[first] == ' ';
|
||||
val indicator := column as i64 - parent;
|
||||
if indicated && indicator > 9 {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.lead();
|
||||
this._text.push('|');
|
||||
if indicated {
|
||||
this._text.push(('0' as u64 + indicator as u64) as u8);
|
||||
}
|
||||
if trailing == 0 {
|
||||
this._text.push('-');
|
||||
} else if trailing > 1 {
|
||||
this._text.push('+');
|
||||
}
|
||||
this._text.push('\n');
|
||||
|
||||
var start: u64 = 0;
|
||||
while start <= body.length {
|
||||
var end := start;
|
||||
while end < body.length && body[end] != '\n' {
|
||||
end++;
|
||||
}
|
||||
if end > start {
|
||||
this.spaces(column);
|
||||
this._text.append(body.substr(start, end - start));
|
||||
}
|
||||
this._text.push('\n');
|
||||
start = end + 1;
|
||||
}
|
||||
for _ in 1..trailing {
|
||||
this._text.push('\n');
|
||||
}
|
||||
this._pending = after_nothing;
|
||||
return true;
|
||||
}
|
||||
|
||||
# Appends a key: plain where it reads back as the same text, and double-quoted
|
||||
# otherwise, giving whether it is UTF-8.
|
||||
def writer::append_key(&mut this, name: strview): bool {
|
||||
if plain_writes(name) {
|
||||
this._text.append(name);
|
||||
return true;
|
||||
}
|
||||
return append_double(name, &mut this._text);
|
||||
}
|
||||
|
||||
def writer::spaces(&mut this, count: u64): void {
|
||||
for _ in 0..count {
|
||||
this._text.push(' ');
|
||||
}
|
||||
}
|
||||
|
||||
def writer::top(&mut this): &mut level {
|
||||
return this._levels.at(this._levels.length - 1);
|
||||
}
|
||||
|
||||
# Keeps the first failure.
|
||||
def writer::keep(&mut this, kind: error_kind): void {
|
||||
if this._failure is none {
|
||||
this._failure = kind;
|
||||
}
|
||||
}
|
||||
|
||||
# Passes the text on to the stream, where the writer passes it on and holds enough.
|
||||
def writer::passes(&mut this): void {
|
||||
if this._pass_at != 0 && this._text.length >= this._pass_at {
|
||||
this.pass();
|
||||
}
|
||||
}
|
||||
|
||||
# Passes everything held on to the stream, and lets go of it. Once the stream has
|
||||
# failed, what is written is let go of without being passed on.
|
||||
def writer::pass(&mut this): void {
|
||||
if this._out is some(out) {
|
||||
if out.write(this._text.span) is error(_) {
|
||||
this._out = nothing {};
|
||||
this.keep(error_kind::not_written);
|
||||
}
|
||||
}
|
||||
this._text.clear();
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
#! @file yaml.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains YAML's errors and limits, and the functions that write a value as YAML and
|
||||
#! read one back by what `@serial` marks of its type, over `std::serial`.
|
||||
#!
|
||||
#! YAML is read as YAML 1.2.2 writes it, by its core schema: a plain scalar is empty,
|
||||
#! a boolean, an integer, a float, or text by how it is written, and a quoted or block
|
||||
#! scalar is always text. `yaml::parse` reads a stream of documents into a
|
||||
#! `yaml::document`, `yaml::reader` gives one event at a time, and `yaml::writer`
|
||||
#! writes YAML in block style as it is given it.
|
||||
|
||||
import std::io;
|
||||
module std::yaml;
|
||||
|
||||
|
||||
#! How deep collections may nest before reading fails with `too_deep`, unless
|
||||
#! the limits given say otherwise.
|
||||
pub const default_depth: u32 = 512;
|
||||
|
||||
#! How many nodes the aliases of a stream may stand for in all before reading
|
||||
#! fails with `too_many_aliases`, unless the limits given say otherwise.
|
||||
pub const default_aliases: u64 = 1000000;
|
||||
|
||||
#! How far reading a stream may go, against text written to exhaust a reader.
|
||||
pub struct limits {
|
||||
pub val depth: u32 = default_depth; #! How deep collections may nest.
|
||||
pub val aliases: u64 = default_aliases; #! How many nodes aliases may stand for, in all.
|
||||
}
|
||||
|
||||
#! Why YAML could not be read or written.
|
||||
pub enum error_kind: u8 {
|
||||
unexpected_end, #! The text ends where something more must follow.
|
||||
unexpected_byte, #! A byte stands where YAML allows none of its kind.
|
||||
invalid_utf8, #! The text is not UTF-8.
|
||||
invalid_character, #! The text holds a character YAML does not allow, as a control character.
|
||||
invalid_escape, #! A double-quoted scalar holds an escape YAML has not.
|
||||
tab_indent, #! A tab indents a line, where only spaces may.
|
||||
wrong_indent, #! A line is indented where nothing open can go on.
|
||||
long_key, #! An implicit key runs over its line, or past 1,024 characters.
|
||||
missing_colon, #! A key that must be one, as a line of a block mapping is, has no `:` after it.
|
||||
unknown_anchor, #! An alias names an anchor not given before it.
|
||||
recursive_alias, #! An alias stands within the node it names.
|
||||
too_many_aliases, #! The aliases stand for more nodes than the limit.
|
||||
invalid_directive, #! A directive is written wrongly, or given twice.
|
||||
unsupported_version, #! The `%YAML` directive names a version this does not read.
|
||||
unknown_handle, #! A tag's handle is not given by a `%TAG` directive.
|
||||
mistagged, #! A scalar's tag names a kind its text is not written as.
|
||||
too_deep, #! Collections nest deeper than the limit.
|
||||
too_long, #! The text is longer than the 4 GiB a document holds.
|
||||
more_documents, #! A stream holds more than the one document asked for.
|
||||
not_written, #! The stream the text was passed on to failed, as its own error says.
|
||||
|
||||
# What `std::serial` finds reading and writing typed values, as its own kinds say.
|
||||
wrong_kind, #! A value is of another kind than the type asked for, as text for a number.
|
||||
missing_member, #! An object lacks a member for a field that is not a `maybe`.
|
||||
unknown_member, #! An object has a member no field takes, which only strict reading refuses.
|
||||
repeated_member, #! An object has a member twice, which only strict reading refuses.
|
||||
out_of_range, #! A number does not fit the type asked for, or a name is no member's.
|
||||
not_serial, #! A value holds an enum member or union field that is not `@serial`.
|
||||
}
|
||||
|
||||
#! Why YAML could not be read or written, and where in the text.
|
||||
#!
|
||||
#! An error is plain data, so `else (e)` names it. One from writing has no
|
||||
#! place, and is at line 0.
|
||||
pub struct error {
|
||||
pub var kind: error_kind; #! What went wrong.
|
||||
pub var offset: u64; #! The byte of the text the error is at.
|
||||
pub var line: u32; #! Counted from 1.
|
||||
pub var column: u32; #! The byte within the line, counted from 1.
|
||||
}
|
||||
|
||||
#! Says what the error is, in a sentence, after where it is.
|
||||
#! @param this The error to describe.
|
||||
#! @returns The description, as `4:3: A tab indents the line, where only spaces
|
||||
#! may.`
|
||||
pub def error::describe(&this): string {
|
||||
if this.line == 0 {
|
||||
return string::from(describe(this.kind), nothing {});
|
||||
}
|
||||
return $"{this.line}:{this.column}: {describe(this.kind)}";
|
||||
}
|
||||
|
||||
#! Says what a kind of error is, in a sentence.
|
||||
#! @param kind The kind to describe.
|
||||
#! @returns The sentence.
|
||||
pub def describe(kind: error_kind): strview {
|
||||
return match kind {
|
||||
unexpected_end => "The text ends where something more must follow.",
|
||||
unexpected_byte => "A byte stands where YAML allows none of its kind.",
|
||||
invalid_utf8 => "The text is not UTF-8.",
|
||||
invalid_character => "The text holds a character YAML does not allow.",
|
||||
invalid_escape => "A double-quoted scalar holds an escape YAML does not have.",
|
||||
tab_indent => "A tab indents the line, where only spaces may.",
|
||||
wrong_indent => "The line is indented where nothing open can go on.",
|
||||
long_key => "An implicit key runs over its line, or past 1,024 characters.",
|
||||
missing_colon => "A key has no `:` after it.",
|
||||
unknown_anchor => "An alias names an anchor not given before it.",
|
||||
recursive_alias => "An alias stands within the node it names.",
|
||||
too_many_aliases => "The aliases stand for more nodes than the limit allows.",
|
||||
invalid_directive => "A directive is written wrongly, or given twice.",
|
||||
unsupported_version => "The `%YAML` directive names a version this does not read.",
|
||||
unknown_handle => "A tag's handle is not given by a `%TAG` directive.",
|
||||
mistagged => "A scalar's tag names a kind its text is not written as.",
|
||||
too_deep => "Collections nest deeper than the limit the text is read with.",
|
||||
too_long => "The text is longer than the 4 GiB a document holds.",
|
||||
more_documents => "The stream holds more than one document.",
|
||||
not_written => "The stream the text was written to failed, as its own error says.",
|
||||
wrong_kind => serial::describe(serial::error_kind::wrong_kind),
|
||||
missing_member => serial::describe(serial::error_kind::missing_member),
|
||||
unknown_member => serial::describe(serial::error_kind::unknown_member),
|
||||
repeated_member => serial::describe(serial::error_kind::repeated_member),
|
||||
out_of_range => serial::describe(serial::error_kind::out_of_range),
|
||||
not_serial => serial::describe(serial::error_kind::not_serial),
|
||||
};
|
||||
}
|
||||
|
||||
#! The error YAML gives for one `std::serial` gives, at the same place.
|
||||
#! @param problem The error reading or writing a typed value gave.
|
||||
#! @returns The error.
|
||||
pub def error::from(problem: &serial::error): error {
|
||||
return error {
|
||||
kind = of_serial(problem.kind),
|
||||
offset = problem.offset,
|
||||
line = problem.line,
|
||||
column = problem.column
|
||||
};
|
||||
}
|
||||
|
||||
# The kind of YAML's error for a kind of `std::serial`'s.
|
||||
def of_serial(kind: serial::error_kind): error_kind {
|
||||
return match kind {
|
||||
wrong_kind => error_kind::wrong_kind,
|
||||
missing_member => error_kind::missing_member,
|
||||
unknown_member => error_kind::unknown_member,
|
||||
repeated_member => error_kind::repeated_member,
|
||||
out_of_range => error_kind::out_of_range,
|
||||
not_serial => error_kind::not_serial,
|
||||
};
|
||||
}
|
||||
|
||||
# An error of a kind at a byte of the text.
|
||||
def error_at(kind: error_kind, text: strview, offset: u64): error {
|
||||
val at := serial::place_of(text, offset);
|
||||
return error { kind = kind, offset = offset, line = at.line, column = at.column };
|
||||
}
|
||||
|
||||
#! Writes a typed value through a writer, by what `@serial` marks of its type,
|
||||
#! or the form of its own the type gives, among whatever else the writer is
|
||||
#! given.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param out The writer to write it with.
|
||||
pub def encode<T>(value: &T, out: &mut writer): void {
|
||||
serial::encode(value, out);
|
||||
}
|
||||
|
||||
#! Writes a typed value as YAML text, by what `@serial` marks of its type.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param indent Spaces for each level of nesting.
|
||||
#! @param alloc An optional allocator for the text to take memory from.
|
||||
#! @returns The text, or the first failure in the value, as an enum member or
|
||||
#! union field that is not marked.
|
||||
pub def to_text<T>(value: &T, indent: u32 = 2, alloc: maybe<&mut allocator> = nothing {}): result<string, error> {
|
||||
var out := writer::new(indent, alloc);
|
||||
serial::encode(value, &mut out);
|
||||
_ = out.finish() else (e) { return e; };
|
||||
return move(out._text);
|
||||
}
|
||||
|
||||
#! Writes a typed value as YAML text into a stream, by what `@serial` marks of
|
||||
#! its type, passing the text on as it goes rather than holding it all.
|
||||
#! @tparam T The type of the value.
|
||||
#! @param value The value to write.
|
||||
#! @param out The stream to write to, which is not flushed: whoever made it
|
||||
#! does that.
|
||||
#! @param indent Spaces for each level of nesting.
|
||||
#! @returns Nothing, or the first failure in the value, or `not_written` where
|
||||
#! the stream failed, as its own error then says.
|
||||
pub def write_to<T>(value: &T, out: &mut writable, indent: u32 = 2): result<void, error> {
|
||||
var w := writer::to(out, indent);
|
||||
serial::encode(value, &mut w);
|
||||
_ = w.finish() else (e) { return e; };
|
||||
return;
|
||||
}
|
||||
|
||||
#! Reads a typed value from a value of a document, by what `@serial` marks of
|
||||
#! its type, or the form of its own the type gives.
|
||||
#! @tparam T The type to read.
|
||||
#! @param from The value to read.
|
||||
#! @param given How strictly to read: strictly, a member no field takes, and a
|
||||
#! member written more than once, are errors.
|
||||
#! @returns The value, or why it could not be read, at the value that failed.
|
||||
pub def decode<T>(from: value, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
|
||||
var made := serial::decode::<T>(&from._document[0], from._at, given) else (e) { return error::from(&e); };
|
||||
return move(made);
|
||||
}
|
||||
|
||||
#! Reads a typed value from YAML text holding one document, by what `@serial`
|
||||
#! marks of its type.
|
||||
#! @tparam T The type to read.
|
||||
#! @param text The text to read.
|
||||
#! @param given How strictly to read.
|
||||
#! @returns The value, or why the text is not YAML, holds more than one
|
||||
#! document, or could not be read as the type.
|
||||
pub def from_text<T>(text: strview, given: serial::options = serial::options {}): result<T, error> where T: zeroable {
|
||||
val read := parse(text) else (e) { return e; };
|
||||
if read.document_count > 1 {
|
||||
return error_at(error_kind::more_documents, text, read.document_start(1));
|
||||
}
|
||||
var made := decode::<T>(read.root, given) else (e) { return e; };
|
||||
return move(made);
|
||||
}
|
||||
Reference in new issue
Block a user