Initial Commit
This commit is contained in:
1624 files changed
+43422
No files matched your search
@@ -0,0 +1,91 @@
|
||||
# std::xml
|
||||
|
||||
`std::xml` reads XML for Sakura, strictly, as XML 1.0 (Fifth Edition) writes it,
|
||||
with its names in namespaces, as Namespaces in XML 1.0 writes them. Text must be
|
||||
UTF-8, and is checked for everything XML asks of a document that is well formed:
|
||||
markup, tags that match, an attribute given once, the characters XML allows,
|
||||
and references to what is declared. `xml::parse` reads text into an
|
||||
`xml::document`, which holds every element, attribute, text, comment, and
|
||||
processing instruction of it, and `xml::reader` gives one token at a time.
|
||||
|
||||
## 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.xml, std.io]
|
||||
```
|
||||
|
||||
```sakura
|
||||
import std::io;
|
||||
import std::xml;
|
||||
|
||||
def main(): void {
|
||||
val read := xml::parse("<list><item id='1'>one</item><item id='2'>two</item></list>") else (e) {
|
||||
io::println($"That isn't XML: {e.describe()}");
|
||||
return;
|
||||
};
|
||||
for item in read.root.elements() {
|
||||
val id := item.attribute("id") else "?";
|
||||
io::println($"{id}: {item.text()}");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
A reader gives the same piece by piece, without building anything:
|
||||
|
||||
```sakura
|
||||
var tokens := xml::reader::new(text);
|
||||
while tokens.next() is some(read) {
|
||||
if read.kind == xml::token_kind::start {
|
||||
for &each in tokens.attributes { io::println($"{read.local}@{each.local} = {each.value}"); }
|
||||
}
|
||||
}
|
||||
if tokens.error is some(e) { io::println(e.describe()); }
|
||||
```
|
||||
|
||||
## What it reads
|
||||
|
||||
- **Text** is UTF-8, after an optional byte order mark. Text whose declaration
|
||||
names another encoding is read while it is ASCII, which it is then the same
|
||||
as, and stops with `unsupported_encoding` at the first byte past. Every line
|
||||
break is read as `\n`.
|
||||
- **Attributes' values** are normalized as XML says: each whitespace character
|
||||
is a space, and references are replaced, so a tab written `	` stays one.
|
||||
- **Text** is decoded: references are replaced, and a CDATA section's text is
|
||||
text like the rest, so the document holds text beside a CDATA section as one
|
||||
node. Whitespace within the root element is text too.
|
||||
- **Namespaces**: each element and attribute has its name as written, its
|
||||
prefix, its local name, and the namespace it is in, and attributes are found
|
||||
by either. `xml::options { namespaces = false }` reads names only as written,
|
||||
for XML that breaks Namespaces in XML.
|
||||
- **The document type** is read: its internal subset's entities are expanded
|
||||
where they are referred to, markup and all, and its attributes' defaults are
|
||||
given to the elements that leave them out, with the spaces of those of types
|
||||
other than CDATA collapsed. Nothing outside the text is read, so a reference
|
||||
to an entity declared only there fails with `undeclared_entity`, and one to an
|
||||
external entity with `external_entity`. Following the specification, after a
|
||||
parameter entity it doesn't read, the declarations that follow are left out,
|
||||
unless the document is standalone.
|
||||
- **Limits**: `xml::options` says how deep elements and entities may nest, 512
|
||||
by default, and how much text the entities a document refers to may stand for
|
||||
in all, 16 MiB by default, so text written to exhaust a reader, as entities
|
||||
that each refer to the last several times, stops with `too_much_expansion`.
|
||||
|
||||
An error says what went wrong and where, by its line and column, or where the
|
||||
document refers to the entity it is within.
|
||||
|
||||
## Testing
|
||||
|
||||
From the standard library's root, `blossom test --suite std.xml` runs them, or:
|
||||
|
||||
```sh
|
||||
sakurac run --lib std=. tests/main.sakura tests/xml/*.sakura
|
||||
```
|
||||
@@ -0,0 +1,552 @@
|
||||
#! @file document.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains the parsed document, which holds every node of XML text as a flat
|
||||
#! array, and `xml::element` and `xml::node`, which read them.
|
||||
|
||||
module std::xml;
|
||||
|
||||
|
||||
#! The kinds of nodes a document holds.
|
||||
pub enum kind: u8 {
|
||||
element, #! An element, which holds attributes, and nodes of its own.
|
||||
text, #! Text, decoded, with what the CDATA sections among it hold.
|
||||
comment, #! A comment.
|
||||
instruction, #! A processing instruction.
|
||||
}
|
||||
|
||||
# What a record is: the kinds of nodes, then the document itself, whose children
|
||||
# are the root element and the comments and instructions around it.
|
||||
enum record_kind: u8 {
|
||||
element,
|
||||
text,
|
||||
comment,
|
||||
instruction,
|
||||
document,
|
||||
}
|
||||
|
||||
# Where a string is in the document's `_strings`.
|
||||
struct piece {
|
||||
var start: u32;
|
||||
var length: u32;
|
||||
}
|
||||
|
||||
# One node of a document, in 52 bytes.
|
||||
#
|
||||
# A node's children follow it, so its `next` is the index just past it and all
|
||||
# it holds, and its next sibling's, so a node is skipped in one step.
|
||||
struct record {
|
||||
var kind: record_kind;
|
||||
var prefix: u32; #! How long the prefix of an element's name is.
|
||||
var name: piece; #! An element's name, or an instruction's target.
|
||||
var value: piece; #! Text, a comment, what follows an instruction's target, or an element's namespace.
|
||||
var parent: u32;
|
||||
var next: u32;
|
||||
var count: u32; #! How many children it holds.
|
||||
var attributes: u32; #! An element's first attribute.
|
||||
var many: u32; #! How many attributes it has.
|
||||
var line: u32;
|
||||
var column: u32;
|
||||
var offset: u32;
|
||||
}
|
||||
|
||||
# An attribute of an element.
|
||||
struct attribute_record {
|
||||
var name: piece;
|
||||
var prefix: u32;
|
||||
var namespace: piece;
|
||||
var value: piece;
|
||||
var specified: bool;
|
||||
var offset: u32;
|
||||
}
|
||||
|
||||
#! XML text read whole, every node of it held as a record of a flat array.
|
||||
#!
|
||||
#! A document holds its own copy of every name and text, so the text it was
|
||||
#! parsed from may go once it is. Elements and nodes it gives refer to it, so they
|
||||
#! are good only while it lives and stays where it is.
|
||||
pub struct document : moveable {
|
||||
var _strings: string;
|
||||
var _records: vector<record>;
|
||||
var _attributes: vector<attribute_record>;
|
||||
var _root: u32;
|
||||
var _version: piece;
|
||||
var _encoding: piece;
|
||||
var _doctype: piece;
|
||||
var _standalone: bool;
|
||||
}
|
||||
|
||||
#! An element of a document.
|
||||
pub struct element {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
}
|
||||
|
||||
#! A node of a document: an element, text, a comment, or a processing
|
||||
#! instruction.
|
||||
pub struct node {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
}
|
||||
|
||||
#! Reads XML text whole into a document.
|
||||
#! @param text The text, which the document copies what it needs of.
|
||||
#! @param given How the text is read, and how far reading may go.
|
||||
#! @param alloc An optional allocator for the document to take memory from.
|
||||
#! @returns The document, or why the text is not XML, with where it fails.
|
||||
pub def parse(text: strview, given: options = options {}, alloc: maybe<&mut allocator> = nothing {}): result<document, error> {
|
||||
var made := document {
|
||||
_strings = string::new(alloc),
|
||||
_records = vector::<record>::new(alloc),
|
||||
_attributes = vector::<attribute_record>::new(alloc)
|
||||
};
|
||||
made._records.append(record { kind = record_kind::document });
|
||||
|
||||
# The open elements, by their records, within the document's own.
|
||||
var open := vector::<u32>::new(alloc);
|
||||
open.append(0);
|
||||
var lines := line_counter { _text = text };
|
||||
var tokens := reader::new(text, given);
|
||||
var namespace := piece {}; # The last namespace kept, which the next name is often in too.
|
||||
while tokens.next() is some(read) {
|
||||
val at := lines.place(read.offset);
|
||||
val parent: u32 = open.last;
|
||||
val index := made._records.length as u32;
|
||||
var added := record {
|
||||
parent = parent,
|
||||
next = index + 1,
|
||||
line = at.line,
|
||||
column = at.column,
|
||||
offset = read.offset as u32
|
||||
};
|
||||
match read.kind {
|
||||
start => {
|
||||
added.kind = record_kind::element;
|
||||
added.name = made.keep(read.name);
|
||||
added.prefix = read.prefix.length as u32;
|
||||
added.value = made.keep_namespace(read.namespace, &mut namespace);
|
||||
added.attributes = made._attributes.length as u32;
|
||||
added.many = tokens.attributes.length as u32;
|
||||
for &held in tokens.attributes {
|
||||
val kept := attribute_record {
|
||||
name = made.keep(held.name),
|
||||
prefix = held.prefix.length as u32,
|
||||
namespace = made.keep_namespace(held.namespace, &mut namespace),
|
||||
value = made.keep(held.value),
|
||||
specified = held.specified,
|
||||
offset = held.offset as u32
|
||||
};
|
||||
made._attributes.append(kept);
|
||||
}
|
||||
if made._root == 0 {
|
||||
made._root = index;
|
||||
}
|
||||
open.append(index);
|
||||
}
|
||||
end => {
|
||||
made._records[parent as u64].next = index;
|
||||
open.truncate();
|
||||
continue;
|
||||
}
|
||||
text => {
|
||||
# Text next to text, as a CDATA section beside the rest, is one node.
|
||||
val last := made._records[index as u64 - 1];
|
||||
if last.kind == record_kind::text && last.parent == parent
|
||||
&& (last.value.start + last.value.length) as u64 == made._strings.length {
|
||||
made._strings.append(read.text);
|
||||
made._records[index as u64 - 1].value.length += read.text.length as u32;
|
||||
continue;
|
||||
}
|
||||
added.kind = record_kind::text;
|
||||
added.value = made.keep(read.text);
|
||||
}
|
||||
comment => {
|
||||
added.kind = record_kind::comment;
|
||||
added.value = made.keep(read.text);
|
||||
}
|
||||
instruction => {
|
||||
added.kind = record_kind::instruction;
|
||||
added.name = made.keep(read.name);
|
||||
added.value = made.keep(read.text);
|
||||
}
|
||||
}
|
||||
made._records[parent as u64].count++;
|
||||
made._records.append(added);
|
||||
}
|
||||
|
||||
if tokens.error is some(failed) {
|
||||
return failed;
|
||||
}
|
||||
if made._strings.length > 0xFFFFFFFFu {
|
||||
return error { kind = error_kind::too_long };
|
||||
}
|
||||
made._records[0].next = made._records.length as u32;
|
||||
made._version = made.keep(tokens.version);
|
||||
made._encoding = made.keep(tokens.encoding);
|
||||
made._doctype = made.keep(tokens.doctype);
|
||||
made._standalone = tokens.standalone;
|
||||
return move(made);
|
||||
}
|
||||
|
||||
#! Creates a document by taking another's records and strings, which leaves the
|
||||
#! other holding nothing.
|
||||
#! @param other The document to move from.
|
||||
#! @returns The document.
|
||||
pub def document::move_of(other: &mut document): document {
|
||||
return document {
|
||||
_strings = move(other._strings),
|
||||
_records = move(other._records),
|
||||
_attributes = move(other._attributes),
|
||||
_root = other._root,
|
||||
_version = other._version,
|
||||
_encoding = other._encoding,
|
||||
_doctype = other._doctype,
|
||||
_standalone = other._standalone
|
||||
};
|
||||
}
|
||||
|
||||
#! The root element, which holds the rest.
|
||||
#! @param this The document to read.
|
||||
#! @returns The element.
|
||||
pub val document::root: element {
|
||||
get => element { _document = this as *document, _at = this._root };
|
||||
}
|
||||
|
||||
#! Iterates over the nodes outside every other: the root element, and the
|
||||
#! comments and processing instructions before and after it, in order.
|
||||
#! @param this The document to walk.
|
||||
#! @returns An iterator over them.
|
||||
pub def document::children(&this): node_cursor {
|
||||
return node_cursor { _document = this as *document, _at = 1, _left = this._records[0].count };
|
||||
}
|
||||
|
||||
#! The version the XML declaration gives, as `1.0`.
|
||||
#! @param this The document to ask.
|
||||
#! @returns The version, or empty where the text has no declaration.
|
||||
pub val document::version: strview {
|
||||
get => this.text_of(this._version);
|
||||
}
|
||||
|
||||
#! The encoding the XML declaration names, as written.
|
||||
#! @param this The document to ask.
|
||||
#! @returns The encoding, or empty where none is named.
|
||||
pub val document::encoding: strview {
|
||||
get => this.text_of(this._encoding);
|
||||
}
|
||||
|
||||
#! Whether the XML declaration says the document stands alone.
|
||||
#! @param this The document to ask.
|
||||
#! @returns Whether it says `standalone="yes"`.
|
||||
pub val document::standalone: bool {
|
||||
get => this._standalone;
|
||||
}
|
||||
|
||||
#! The name the document type gives the root element.
|
||||
#! @param this The document to ask.
|
||||
#! @returns The name, or empty where the text has no document type.
|
||||
pub val document::doctype: strview {
|
||||
get => this.text_of(this._doctype);
|
||||
}
|
||||
|
||||
#! The element's name as written, as `svg:rect`.
|
||||
#! @param this The element to ask.
|
||||
#! @returns The name.
|
||||
pub val element::name: strview {
|
||||
get => (*this._document).text_of((*this._document).record_at(this._at).name);
|
||||
}
|
||||
|
||||
#! The prefix of the element's name.
|
||||
#! @param this The element to ask.
|
||||
#! @returns The prefix, or empty where it has none.
|
||||
pub val element::prefix: strview {
|
||||
get => this.name.substr(0, (*this._document).record_at(this._at).prefix as u64);
|
||||
}
|
||||
|
||||
#! The element's name without its prefix, as `rect` of `svg:rect`.
|
||||
#! @param this The element to ask.
|
||||
#! @returns The local name.
|
||||
pub val element::local: strview {
|
||||
get => local_of(this.name, (*this._document).record_at(this._at).prefix);
|
||||
}
|
||||
|
||||
#! The namespace the element's name is in.
|
||||
#! @param this The element to ask.
|
||||
#! @returns The namespace's name, or empty where it is in none.
|
||||
pub val element::namespace: strview {
|
||||
get => (*this._document).text_of((*this._document).record_at(this._at).value);
|
||||
}
|
||||
|
||||
#! Where the element's start tag is in the text it was read from.
|
||||
#! @param this The element to ask.
|
||||
#! @returns Where it is, or where the entity holding it is referred to.
|
||||
pub val element::place: place {
|
||||
get => (*this._document).place_at(this._at);
|
||||
}
|
||||
|
||||
#! The element holding this one.
|
||||
#! @param this The element to ask.
|
||||
#! @returns The element, or `nothing` for the root element.
|
||||
pub val element::parent: maybe<element> {
|
||||
get {
|
||||
val held := (*this._document).record_at(this._at).parent;
|
||||
if held == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
return element { _document = this._document, _at = held };
|
||||
}
|
||||
}
|
||||
|
||||
#! Finds the value of an attribute by its name as written, as `xlink:href`.
|
||||
#! @param this The element to look in.
|
||||
#! @param name The name.
|
||||
#! @returns The value, or `nothing` where the element has no such attribute.
|
||||
pub def element::attribute(&this, name: strview): maybe<strview> {
|
||||
val doc := this._document;
|
||||
val held := (*doc).record_at(this._at);
|
||||
for index in held.attributes..(held.attributes + held.many) {
|
||||
val kept := &(*doc)._attributes[index as u64];
|
||||
if (*doc).text_of(kept.name) == name {
|
||||
return (*doc).text_of(kept.value);
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Finds the value of an attribute by its namespace and local name, whatever
|
||||
#! prefix it is written with.
|
||||
#! @param this The element to look in.
|
||||
#! @param namespace The namespace's name, or empty for an attribute in none, as
|
||||
#! one without a prefix is.
|
||||
#! @param local The name without its prefix.
|
||||
#! @returns The value, or `nothing` where the element has no such attribute.
|
||||
pub def element::attribute(&this, namespace: strview, local: strview): maybe<strview> {
|
||||
val doc := this._document;
|
||||
val held := (*doc).record_at(this._at);
|
||||
for index in held.attributes..(held.attributes + held.many) {
|
||||
val kept := &(*doc)._attributes[index as u64];
|
||||
if (*doc).text_of(kept.namespace) == namespace && local_of((*doc).text_of(kept.name), kept.prefix) == local {
|
||||
return (*doc).text_of(kept.value);
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! Iterates over the element's attributes: those its tag gives, in order, then
|
||||
#! the defaults the document type gives for those it does not.
|
||||
#! @param this The element to read.
|
||||
#! @returns An iterator over them.
|
||||
pub def element::attributes(&this): attribute_cursor {
|
||||
val held := (*this._document).record_at(this._at);
|
||||
return attribute_cursor { _document = this._document, _at = held.attributes, _left = held.many };
|
||||
}
|
||||
|
||||
#! Iterates over the nodes the element holds, in order.
|
||||
#! @param this The element to walk.
|
||||
#! @returns An iterator over them.
|
||||
pub def element::children(&this): node_cursor {
|
||||
return node_cursor { _document = this._document, _at = this._at + 1, _left = (*this._document).record_at(this._at).count };
|
||||
}
|
||||
|
||||
#! Iterates over the elements the element holds, in order, leaving out its text,
|
||||
#! comments, and instructions.
|
||||
#! @param this The element to walk.
|
||||
#! @returns An iterator over them.
|
||||
pub def element::elements(&this): element_cursor {
|
||||
return element_cursor { _document = this._document, _at = this._at + 1, _left = (*this._document).record_at(this._at).count };
|
||||
}
|
||||
|
||||
#! Finds the first element the element holds with a name as written.
|
||||
#! @param this The element to look in.
|
||||
#! @param name The name.
|
||||
#! @returns The element, or `nothing` where it holds none of the name.
|
||||
pub def element::child(&this, name: strview): maybe<element> {
|
||||
for each in this.elements() {
|
||||
if each.name == name {
|
||||
return each;
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! The text the element holds, within the elements it holds too, in order, as
|
||||
#! the DOM's `textContent` gives it.
|
||||
#! @param this The element to read.
|
||||
#! @param alloc An optional allocator for the text to take memory from.
|
||||
#! @returns The text.
|
||||
pub def element::text(&this, alloc: maybe<&mut allocator> = nothing {}): string {
|
||||
var made := string::new(alloc);
|
||||
val doc := this._document;
|
||||
val end := (*doc).record_at(this._at).next;
|
||||
for index in (this._at + 1)..end {
|
||||
val held := (*doc).record_at(index);
|
||||
if held.kind == record_kind::text {
|
||||
made.append((*doc).text_of(held.value));
|
||||
}
|
||||
}
|
||||
return made;
|
||||
}
|
||||
|
||||
#! The node the element is.
|
||||
#! @param this The element.
|
||||
#! @returns The node.
|
||||
pub def element::as_node(&this): node {
|
||||
return node { _document = this._document, _at = this._at };
|
||||
}
|
||||
|
||||
#! What kind of node the node is.
|
||||
#! @param this The node to ask.
|
||||
#! @returns Its kind.
|
||||
pub val node::kind: kind {
|
||||
get => ((*this._document).record_at(this._at).kind as u8) as kind;
|
||||
}
|
||||
|
||||
#! The element the node is.
|
||||
#! @param this The node to ask.
|
||||
#! @returns The element, or `nothing` where the node is no element.
|
||||
pub def node::as_element(&this): maybe<element> {
|
||||
if (*this._document).record_at(this._at).kind != record_kind::element {
|
||||
return nothing {};
|
||||
}
|
||||
return element { _document = this._document, _at = this._at };
|
||||
}
|
||||
|
||||
#! An element's name as written, or a processing instruction's target.
|
||||
#! @param this The node to ask.
|
||||
#! @returns The name, or empty for text and comments.
|
||||
pub val node::name: strview {
|
||||
get => (*this._document).text_of((*this._document).record_at(this._at).name);
|
||||
}
|
||||
|
||||
#! Text's text, a comment's, or what follows a processing instruction's target.
|
||||
#! @param this The node to ask.
|
||||
#! @returns The text, or empty for an element, whose text `element::text` gives.
|
||||
pub val node::text: strview {
|
||||
get {
|
||||
val held := (*this._document).record_at(this._at);
|
||||
if held.kind == record_kind::element {
|
||||
return "";
|
||||
}
|
||||
return (*this._document).text_of(held.value);
|
||||
}
|
||||
}
|
||||
|
||||
#! Where the node is in the text it was read from.
|
||||
#! @param this The node to ask.
|
||||
#! @returns Where it is, or where the entity holding it is referred to.
|
||||
pub val node::place: place {
|
||||
get => (*this._document).place_at(this._at);
|
||||
}
|
||||
|
||||
#! An iterator over nodes, in order.
|
||||
pub struct node_cursor : iter<node> {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
var _left: u32;
|
||||
}
|
||||
|
||||
#! Gives the next node.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next node, or `nothing` once there are no more.
|
||||
pub def node_cursor::next(&mut this): maybe<node> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
val made := node { _document = this._document, _at = this._at };
|
||||
this._at = (*this._document).record_at(this._at).next;
|
||||
this._left--;
|
||||
return made;
|
||||
}
|
||||
|
||||
#! An iterator over elements, in order.
|
||||
pub struct element_cursor : iter<element> {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
var _left: u32; #! How many nodes are left, elements or not.
|
||||
}
|
||||
|
||||
#! Gives the next element.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next element, or `nothing` once there are no more.
|
||||
pub def element_cursor::next(&mut this): maybe<element> {
|
||||
while this._left > 0 {
|
||||
val at := this._at;
|
||||
val held := (*this._document).record_at(at);
|
||||
this._at = held.next;
|
||||
this._left--;
|
||||
if held.kind == record_kind::element {
|
||||
return element { _document = this._document, _at = at };
|
||||
}
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
#! An iterator over an element's attributes, in order.
|
||||
pub struct attribute_cursor : iter<attribute> {
|
||||
var _document: *document;
|
||||
var _at: u32;
|
||||
var _left: u32;
|
||||
}
|
||||
|
||||
#! Gives the next attribute.
|
||||
#! @param this The iterator to advance.
|
||||
#! @returns The next attribute, or `nothing` once there are no more.
|
||||
pub def attribute_cursor::next(&mut this): maybe<attribute> {
|
||||
if this._left == 0 {
|
||||
return nothing {};
|
||||
}
|
||||
val doc := this._document;
|
||||
val kept := &(*doc)._attributes[this._at as u64];
|
||||
val name := (*doc).text_of(kept.name);
|
||||
this._at++;
|
||||
this._left--;
|
||||
return attribute {
|
||||
name = name,
|
||||
prefix = name.substr(0, kept.prefix as u64),
|
||||
local = local_of(name, kept.prefix),
|
||||
namespace = (*doc).text_of(kept.namespace),
|
||||
value = (*doc).text_of(kept.value),
|
||||
specified = kept.specified,
|
||||
offset = kept.offset as u64
|
||||
};
|
||||
}
|
||||
|
||||
# Keeps a copy of text among the document's strings.
|
||||
def document::keep(&mut this, text: strview): piece {
|
||||
val start := this._strings.length as u32;
|
||||
this._strings.append(text);
|
||||
return piece { start = start, length = text.length as u32 };
|
||||
}
|
||||
|
||||
# Keeps a namespace's name, unless it is the last kept, whose copy serves.
|
||||
def document::keep_namespace(&mut this, name: strview, last: &mut piece): piece {
|
||||
if name.length == 0 {
|
||||
return piece {};
|
||||
}
|
||||
if this.text_of(last) != name {
|
||||
last = this.keep(name);
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
def document::text_of(&this, at: piece): strview {
|
||||
return this._strings.substr(at.start as u64, at.length as u64);
|
||||
}
|
||||
|
||||
def document::record_at(&this, at: u32): &record {
|
||||
return &this._records[at as u64];
|
||||
}
|
||||
|
||||
def document::place_at(&this, at: u32): place {
|
||||
val held := this.record_at(at);
|
||||
return place { offset = held.offset as u64, line = held.line, column = held.column };
|
||||
}
|
||||
|
||||
# A name without the prefix it has of a length.
|
||||
def local_of(name: strview, prefix: u32): strview {
|
||||
if prefix == 0 {
|
||||
return name;
|
||||
}
|
||||
return name.substr(prefix as u64 + 1, name.length - prefix as u64 - 1);
|
||||
}
|
||||
+1882
File diff suppressed because it is too large.
Load diff
+262
@@ -0,0 +1,262 @@
|
||||
#! @file text.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains what XML's text is made of: UTF-8, the characters XML allows, those
|
||||
#! names are made of, and escaping text to write it as XML.
|
||||
|
||||
module std::xml;
|
||||
|
||||
|
||||
#! The namespace the prefix `xml` is bound to, in every document.
|
||||
pub const xml_namespace: strview = "http://www.w3.org/XML/1998/namespace";
|
||||
|
||||
#! The namespace of the attributes binding namespaces, as `xmlns:svg`.
|
||||
pub const xmlns_namespace: strview = "http://www.w3.org/2000/xmlns/";
|
||||
|
||||
# What breaks XML's text, and where.
|
||||
struct disallowed {
|
||||
var kind: error_kind;
|
||||
var offset: u64;
|
||||
}
|
||||
|
||||
#! Writes text as XML, escaping what would be read as markup or changed by
|
||||
#! reading: `&`, `<`, and `>` always, and a `\r`, which reading would make a
|
||||
#! `\n`. Within an attribute's value, written between double quotes, `"` is
|
||||
#! escaped too, and `\t` and `\n`, which reading would make spaces.
|
||||
#! @param text The text, which is written as it is otherwise, so it must
|
||||
#! hold only characters XML allows.
|
||||
#! @param into The string to append to.
|
||||
#! @param attribute Whether the text is an attribute's value.
|
||||
pub def escape(text: strview, into: &mut string, attribute: bool = false): void {
|
||||
var run: u64 = 0;
|
||||
for at in 0..text.length {
|
||||
val byte := text[at];
|
||||
val written: strview = match byte {
|
||||
'&' => "&",
|
||||
'<' => "<",
|
||||
'>' => ">",
|
||||
'\r' => " ",
|
||||
'"' => attribute ? """ : "",
|
||||
'\t' => attribute ? "	" : "",
|
||||
'\n' => attribute ? " " : "",
|
||||
else => "",
|
||||
};
|
||||
if written.length != 0 {
|
||||
into.append(text.substr(run, at - run));
|
||||
into.append(written);
|
||||
run = at + 1;
|
||||
}
|
||||
}
|
||||
into.append(text.substr(run, text.length - run));
|
||||
}
|
||||
|
||||
# The first place text breaks UTF-8, or holds a character XML does not allow.
|
||||
def first_disallowed(text: strview): maybe<disallowed> {
|
||||
var at: u64 = 0;
|
||||
while at < text.length {
|
||||
val byte := text[at];
|
||||
if byte >= 0x20 && byte < 0x80 {
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
if byte < 0x20 {
|
||||
if byte != '\t' && byte != '\n' && byte != '\r' {
|
||||
return disallowed { kind = error_kind::invalid_character, offset = at };
|
||||
}
|
||||
at++;
|
||||
continue;
|
||||
}
|
||||
|
||||
val count := utf8_length(text, at);
|
||||
if count == 0 {
|
||||
return disallowed { kind = error_kind::invalid_utf8, offset = at };
|
||||
}
|
||||
if !is_char(code_at(text, at)) {
|
||||
return disallowed { kind = error_kind::invalid_character, offset = at };
|
||||
}
|
||||
at += count;
|
||||
}
|
||||
return nothing {};
|
||||
}
|
||||
|
||||
# The length of the UTF-8 sequence beginning at a byte, or 0 where the bytes
|
||||
# there are not one: overlong, a surrogate, past U+10FFFF, or cut short.
|
||||
def utf8_length(text: strview, at: u64): u64 {
|
||||
val lead := text[at];
|
||||
if lead < 0x80 {
|
||||
return 1;
|
||||
}
|
||||
|
||||
# The second byte is narrowed where the lead alone would allow an overlong form,
|
||||
# a surrogate, or a character past U+10FFFF.
|
||||
var count: u64 = 0;
|
||||
var low: u8 = 0x80;
|
||||
var high: u8 = 0xBF;
|
||||
if lead >= 0xC2 && lead <= 0xDF {
|
||||
count = 2;
|
||||
} else if lead == 0xE0 {
|
||||
count = 3;
|
||||
low = 0xA0;
|
||||
} else if lead == 0xED {
|
||||
count = 3;
|
||||
high = 0x9F;
|
||||
} else if lead >= 0xE1 && lead <= 0xEF {
|
||||
count = 3;
|
||||
} else if lead == 0xF0 {
|
||||
count = 4;
|
||||
low = 0x90;
|
||||
} else if lead == 0xF4 {
|
||||
count = 4;
|
||||
high = 0x8F;
|
||||
} else if lead >= 0xF1 && lead <= 0xF3 {
|
||||
count = 4;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if at + count > text.length {
|
||||
return 0;
|
||||
}
|
||||
val second := text[at + 1];
|
||||
if second < low || second > high {
|
||||
return 0;
|
||||
}
|
||||
for index in 2..count {
|
||||
val next := text[at + index];
|
||||
if next < 0x80 || next > 0xBF {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
# The character whose UTF-8 begins at a byte, which must be UTF-8.
|
||||
def code_at(text: strview, at: u64): u32 {
|
||||
val lead := text[at] as u32;
|
||||
if lead < 0x80 {
|
||||
return lead;
|
||||
}
|
||||
if lead < 0xE0 {
|
||||
return ((lead & 0x1F) << 6) | (text[at + 1] as u32 & 0x3F);
|
||||
}
|
||||
if lead < 0xF0 {
|
||||
return ((lead & 0x0F) << 12) | ((text[at + 1] as u32 & 0x3F) << 6) | (text[at + 2] as u32 & 0x3F);
|
||||
}
|
||||
return ((lead & 0x07) << 18) | ((text[at + 1] as u32 & 0x3F) << 12) | ((text[at + 2] as u32 & 0x3F) << 6)
|
||||
| (text[at + 3] as u32 & 0x3F);
|
||||
}
|
||||
|
||||
# How many bytes of UTF-8 the character beginning with a byte takes.
|
||||
def width_of(lead: u8): u64 {
|
||||
if lead < 0x80 {
|
||||
return 1;
|
||||
}
|
||||
if lead < 0xE0 {
|
||||
return 2;
|
||||
}
|
||||
return lead < 0xF0 ? 3 : 4;
|
||||
}
|
||||
|
||||
# Appends a character as UTF-8.
|
||||
def append_utf8(code: u32, into: &mut string): void {
|
||||
if code < 0x80 {
|
||||
into.push(code as u8);
|
||||
} else if code < 0x800 {
|
||||
into.push((0xC0 | (code >> 6)) as u8);
|
||||
into.push((0x80 | (code & 0x3F)) as u8);
|
||||
} else if code < 0x10000 {
|
||||
into.push((0xE0 | (code >> 12)) as u8);
|
||||
into.push((0x80 | ((code >> 6) & 0x3F)) as u8);
|
||||
into.push((0x80 | (code & 0x3F)) as u8);
|
||||
} else {
|
||||
into.push((0xF0 | (code >> 18)) as u8);
|
||||
into.push((0x80 | ((code >> 12) & 0x3F)) as u8);
|
||||
into.push((0x80 | ((code >> 6) & 0x3F)) as u8);
|
||||
into.push((0x80 | (code & 0x3F)) as u8);
|
||||
}
|
||||
}
|
||||
|
||||
# Whether XML allows a character: `Char`, which leaves out most control
|
||||
# characters, surrogates, U+FFFE, and U+FFFF.
|
||||
def is_char(code: u32): bool {
|
||||
if code < 0x20 {
|
||||
return code == 0x09 || code == 0x0A || code == 0x0D;
|
||||
}
|
||||
return code <= 0xD7FF || (code >= 0xE000 && code <= 0xFFFD) || (code >= 0x10000 && code <= 0x10FFFF);
|
||||
}
|
||||
|
||||
# Whether a byte is whitespace, `S`: a space, a tab, or a line break.
|
||||
def is_space(byte: u8): bool {
|
||||
return byte == ' ' || byte == '\t' || byte == '\n' || byte == '\r';
|
||||
}
|
||||
|
||||
# Whether a character may begin a name, `NameStartChar`.
|
||||
def is_name_start(code: u32): bool {
|
||||
if code < 0x80 {
|
||||
return (code >= 'a' && code <= 'z') || (code >= 'A' && code <= 'Z') || code == '_' || code == ':';
|
||||
}
|
||||
return (code >= 0xC0 && code <= 0xD6) || (code >= 0xD8 && code <= 0xF6) || (code >= 0xF8 && code <= 0x2FF)
|
||||
|| (code >= 0x370 && code <= 0x37D) || (code >= 0x37F && code <= 0x1FFF) || (code >= 0x200C && code <= 0x200D)
|
||||
|| (code >= 0x2070 && code <= 0x218F) || (code >= 0x2C00 && code <= 0x2FEF) || (code >= 0x3001 && code <= 0xD7FF)
|
||||
|| (code >= 0xF900 && code <= 0xFDCF) || (code >= 0xFDF0 && code <= 0xFFFD) || (code >= 0x10000 && code <= 0xEFFFF);
|
||||
}
|
||||
|
||||
# Whether a character may stand within a name, `NameChar`.
|
||||
def is_name_char(code: u32): bool {
|
||||
if code < 0x80 {
|
||||
return (code >= 'a' && code <= 'z') || (code >= 'A' && code <= 'Z') || (code >= '0' && code <= '9')
|
||||
|| code == '_' || code == ':' || code == '-' || code == '.';
|
||||
}
|
||||
return is_name_start(code) || code == 0xB7 || (code >= 0x300 && code <= 0x36F) || (code >= 0x203F && code <= 0x2040);
|
||||
}
|
||||
|
||||
# Where the name beginning at a byte ends, or the byte itself where none begins
|
||||
# there. The text must be UTF-8.
|
||||
def name_end(text: strview, at: u64): u64 {
|
||||
if at >= text.length || !is_name_start(code_at(text, at)) {
|
||||
return at;
|
||||
}
|
||||
return name_chars_end(text, at + width_of(text[at]));
|
||||
}
|
||||
|
||||
# Where a run of characters that may stand within a name, beginning at a byte,
|
||||
# ends: a name token, `Nmtoken`, where it is not empty.
|
||||
def name_chars_end(text: strview, at: u64): u64 {
|
||||
var index := at;
|
||||
while index < text.length {
|
||||
val byte := text[index];
|
||||
if byte < 0x80 {
|
||||
if !is_name_char(byte as u32) {
|
||||
return index;
|
||||
}
|
||||
index++;
|
||||
continue;
|
||||
}
|
||||
if !is_name_char(code_at(text, index)) {
|
||||
return index;
|
||||
}
|
||||
index += width_of(byte);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
# Whether a name is one Namespaces in XML allows an element or attribute: a
|
||||
# local name, or a prefix and one, each of which begins as a name does.
|
||||
def is_qualified(name: strview): bool {
|
||||
val colon := name.find(":") else { return true; };
|
||||
if colon == 0 || colon + 1 >= name.length {
|
||||
return false;
|
||||
}
|
||||
val local := name.substr(colon + 1, name.length - colon - 1);
|
||||
return local.find(":") is none && is_name_start(code_at(local, 0));
|
||||
}
|
||||
|
||||
# Whether a byte may stand in a public identifier, `PubidChar`.
|
||||
def is_public_char(byte: u8): bool {
|
||||
if byte.is_alnum {
|
||||
return true;
|
||||
}
|
||||
return byte.matches(' ', '\r', '\n', '-', '\'', '(', ')', '+', ',', '.', '/', ':', '=', '?', ';', '!', '*', '#', '@', '$', '_', '%');
|
||||
}
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
#! @file xml.sakura
|
||||
#! @author John Christman (sorakatadzuma@gmail.com)
|
||||
#! @copyright Malunal Studios, LLC.
|
||||
#! @license MIT
|
||||
#!
|
||||
#! Contains XML's errors and options, and where in the text something is.
|
||||
#!
|
||||
#! XML is read strictly, as XML 1.0 (Fifth Edition) writes it, with its names in
|
||||
#! namespaces, as Namespaces in XML 1.0 writes them. Text must be UTF-8, and is
|
||||
#! checked for what XML allows: well-formed markup, matching tags, attributes
|
||||
#! given once, and references to what is declared. The document type's internal
|
||||
#! subset is read, and its entities, its attributes' defaults, and how they're
|
||||
#! normalized are used; nothing outside the text is read, so a reference to an
|
||||
#! entity declared only there is an error. `xml::parse` reads text into an
|
||||
#! `xml::document`, which holds every element, attribute, and text of it, and
|
||||
#! `xml::reader` gives one token at a time.
|
||||
|
||||
module std::xml;
|
||||
|
||||
|
||||
#! How deep elements, and entities within entities, may nest before reading
|
||||
#! fails with `too_deep`, unless the options given say otherwise.
|
||||
pub const default_depth: u32 = 512;
|
||||
|
||||
#! How many bytes of their texts the entities a document refers to may stand
|
||||
#! for in all before reading fails with `too_much_expansion`, unless the options
|
||||
#! given say otherwise: 16 MiB.
|
||||
pub const default_expansion: u64 = 0x1000000;
|
||||
|
||||
#! How a document is read, and how far reading it may go, against text written
|
||||
#! to exhaust a reader.
|
||||
pub struct options {
|
||||
pub val depth: u32 = default_depth; #! How deep elements, and entities within entities, may nest.
|
||||
pub val expansion: u64 = default_expansion; #! How many bytes entities' texts may stand for, in all.
|
||||
pub val namespaces: bool = true; #! Whether names are read into namespaces, as Namespaces in XML says.
|
||||
}
|
||||
|
||||
#! Why XML could not be read.
|
||||
pub enum error_kind: u8 {
|
||||
unexpected_end, #! The text ends where something more must follow, as within an open element.
|
||||
unexpected_byte, #! A byte stands where XML allows none of its kind.
|
||||
invalid_utf8, #! The text is not UTF-8.
|
||||
invalid_character, #! The text holds, or a reference names, a character XML does not allow.
|
||||
unsupported_encoding, #! The text is in an encoding other than UTF-8, by its byte order mark or its declaration.
|
||||
invalid_declaration, #! The XML declaration is written wrongly, or a processing instruction named `xml` stands elsewhere.
|
||||
invalid_reference, #! An `&` begins no reference XML writes, as `&name;`, ` `, or `
` do.
|
||||
undeclared_entity, #! A reference names an entity nothing in the text declares.
|
||||
external_entity, #! A reference names an entity whose text is outside the document, which is not read.
|
||||
recursive_entity, #! An entity refers to itself, or to one that refers to it.
|
||||
unbalanced_entity, #! An entity's text ends within an element it began, or ends one it did not.
|
||||
too_much_expansion, #! The entities referred to stand for more text than the limit.
|
||||
mismatched_tag, #! An end tag names another element than the one open.
|
||||
repeated_attribute, #! An element gives an attribute twice, or two whose names are the same in namespaces.
|
||||
text_outside_root, #! Text stands before or after the root element, where only whitespace may.
|
||||
no_root, #! The text holds no element.
|
||||
second_root, #! An element follows the root element, where only one may stand.
|
||||
invalid_name, #! A name holds a colon where namespaces allow none, as an entity's, or more than one.
|
||||
unbound_prefix, #! A name's prefix is bound to no namespace.
|
||||
invalid_namespace, #! A namespace is bound against Namespaces in XML, as `xmlns` is, or a prefix to no name.
|
||||
too_deep, #! Elements, or entities within entities, nest deeper than the limit.
|
||||
too_long, #! The text is longer than the 4 GiB a document holds.
|
||||
}
|
||||
|
||||
#! Why XML could not be read, and where in the text.
|
||||
#!
|
||||
#! An error is plain data, so `else (e)` names it. One within an entity's text
|
||||
#! is where the document refers to the entity.
|
||||
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.
|
||||
}
|
||||
|
||||
#! Where in the text something is.
|
||||
pub struct place {
|
||||
pub var offset: u64; #! The byte of the text.
|
||||
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 `3:7: An end tag names another element than the
|
||||
#! one open.`
|
||||
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 XML allows none of its kind.",
|
||||
invalid_utf8 => "The text is not UTF-8.",
|
||||
invalid_character => "The text holds, or a reference names, a character XML does not allow.",
|
||||
unsupported_encoding => "The text is in an encoding other than UTF-8.",
|
||||
invalid_declaration => "The XML declaration is written wrongly, or a processing instruction named `xml` stands elsewhere.",
|
||||
invalid_reference => "An `&` begins no reference XML writes.",
|
||||
undeclared_entity => "A reference names an entity nothing in the text declares.",
|
||||
external_entity => "A reference names an entity whose text is outside the document, which is not read.",
|
||||
recursive_entity => "An entity refers to itself, or to one that refers to it.",
|
||||
unbalanced_entity => "An entity's text ends within an element it began, or ends one it did not.",
|
||||
too_much_expansion => "The entities referred to stand for more text than the limit the text is read with.",
|
||||
mismatched_tag => "An end tag names another element than the one open.",
|
||||
repeated_attribute => "An element gives an attribute twice.",
|
||||
text_outside_root => "Text stands outside the root element, where only whitespace may.",
|
||||
no_root => "The text holds no element.",
|
||||
second_root => "An element follows the root element, where only one may stand.",
|
||||
invalid_name => "A name holds a colon where namespaces allow none.",
|
||||
unbound_prefix => "A name's prefix is bound to no namespace.",
|
||||
invalid_namespace => "A namespace is bound as Namespaces in XML does not allow.",
|
||||
too_deep => "Elements or entities nest deeper than the limit the text is read with.",
|
||||
too_long => "The text is longer than the 4 GiB a document holds.",
|
||||
};
|
||||
}
|
||||
|
||||
#! Where a byte of text is, by its line and its column. A line ends at `\n`, at
|
||||
#! `\r\n`, or at a `\r` alone.
|
||||
#! @param text The text.
|
||||
#! @param offset The byte, which may be the text's length, for its end.
|
||||
#! @returns Where it is.
|
||||
pub def place_of(text: strview, offset: u64): place {
|
||||
var lines := line_counter { _text = text };
|
||||
return lines.place(offset);
|
||||
}
|
||||
|
||||
# Counts lines up to places further and further on, so finding each costs only
|
||||
# the text since the last.
|
||||
struct line_counter {
|
||||
var _text: strview;
|
||||
var _at: u64;
|
||||
var _line: u32 = 1;
|
||||
var _begun: u64; #! Where the current line begins.
|
||||
}
|
||||
|
||||
# Where a byte at or after the last asked for is.
|
||||
def line_counter::place(&mut this, offset: u64): place {
|
||||
val end := offset < this._text.length ? offset : this._text.length;
|
||||
while this._at < end {
|
||||
val byte := this._text[this._at];
|
||||
if byte == '\n' || (byte == '\r' && (this._at + 1 >= this._text.length || this._text[this._at + 1] != '\n')) {
|
||||
this._line++;
|
||||
this._begun = this._at + 1;
|
||||
}
|
||||
this._at++;
|
||||
}
|
||||
return place { offset = offset, line = this._line, column = (offset - this._begun + 1) as u32 };
|
||||
}
|
||||
|
||||
# An error of a kind at a byte of the text.
|
||||
def error_at(kind: error_kind, text: strview, offset: u64): error {
|
||||
val at := place_of(text, offset);
|
||||
return error { kind = kind, offset = offset, line = at.line, column = at.column };
|
||||
}
|
||||
Reference in new issue
Block a user