Files
std/xml/reader.sakura
T
2026-11-10 12:26:50 -06:00

1883 lines
59 KiB
Plaintext

#! @file reader.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the pull reader, which reads XML one token at a time, checking it as
#! it goes: its elements and attributes, text, comments, and processing
#! instructions, with the document type's internal subset read on the way, and
#! the entities it declares expanded where they are referred to.
import std::containers;
module std::xml;
#! What a token is.
pub enum token_kind: u8 {
start, #! A start tag, or an empty element's tag, whose attributes `reader::attributes` gives.
end, #! An end tag, or the end of an empty element, which follows its start at once.
text, #! Character data, decoded, as what a CDATA section holds is.
comment, #! A comment, whose text is `text`.
instruction, #! A processing instruction, whose target is `name`, and what follows it `text`.
}
#! A piece of XML a reader gives.
#!
#! What it views is good until the next token: the text read, or the reader's
#! own memory, where the token's text was decoded.
pub struct token {
pub var kind: token_kind; #! What the token is.
pub var empty: bool; #! Whether a start tag is an empty element's, as `<br/>` is.
pub var cdata: bool; #! Whether text is what a CDATA section holds.
pub var name: strview; #! An element's name as written, as `svg:rect`, or an instruction's target.
pub var prefix: strview; #! The prefix of an element's name, or empty.
pub var local: strview; #! An element's name without its prefix.
pub var namespace: strview; #! The namespace an element's name is in, or empty for none.
pub var text: strview; #! Text, a comment, or what follows an instruction's target, decoded.
pub var offset: u64; #! The byte of the text it begins at, or where the entity holding it is referred to.
}
#! An attribute of an element.
pub struct attribute {
pub var name: strview; #! As written, as `xlink:href`.
pub var prefix: strview; #! The name's prefix, or empty.
pub var local: strview; #! The name without its prefix.
pub var namespace: strview; #! The namespace the name is in, or empty for none, as a name without a prefix is in.
pub var value: strview; #! The value, with its references replaced and its whitespace normalized.
pub var specified: bool; #! Whether the tag gives it, rather than the document type giving its default.
pub var offset: u64; #! The byte of the text its name begins at, or its tag's, for a default.
}
# What the reader looks for next.
enum reading: u8 {
start, #! The XML declaration, which only the very start of the text may hold.
prolog, #! The document type, comments, and instructions, before the root element.
content, #! What an element holds.
epilog, #! Comments and instructions, after the root element.
done, #! Nothing: the text has been read.
failed, #! Nothing: the reader has stopped at an error.
}
# The index of nothing, in the reader's tables.
const no_index: u32 = 0xFFFFFFFF;
# Text the reader went into another's from, as an entity's from where it is
# referred to.
struct input {
var text: strview; #! The text to go back to.
var at: u64; #! Where reading goes on in it.
var reference: u64; #! Where in it the reference is.
}
# An entity whose text is being read, so a reference to it within is recursion.
struct opened {
var name: strview;
var parameter: bool;
}
# An entity the document type declares.
struct entity {
var name: strview;
var text: strview; #! Its replacement text, which the reader holds.
var external: bool; #! Whether its text is outside the document.
var unparsed: bool; #! Whether it is not XML, as `NDATA` says.
}
# An attribute the document type declares for an element.
struct declared {
var name: strview;
var cdata: bool; #! Whether its values are kept as they are, rather than their spaces collapsed.
var value: maybe<strview>; #! Its default, normalized, where it has one.
var next: u32; #! The next declared for the same element, or `no_index`.
}
# A namespace bound to a prefix, whose name the reader's `_uris` holds.
struct binding {
var prefix: strview;
var start: u64;
var length: u64;
}
# An element whose end tag has not been read.
struct open_element {
var name: strview;
var prefix: strview;
var local: strview;
var level: u64; #! How many inputs deep its start tag is.
var bindings: u64; #! How many namespaces were bound before it.
var uris: u64; #! How long `_uris` was before it.
var offset: u64;
}
# Where an attribute's value is while its tag is read: in the reader's `_values`
# where it was decoded, and in the text read otherwise.
struct value_span {
var start: u64;
var length: u64;
var decoded: bool;
}
# A reference: to a character, which `code` is, or to an entity by `name`.
struct referral {
var code: u32;
var name: strview;
var end: u64; #! Just past its `;`.
}
#! Reads XML one token at a time, checking it as it goes, and stopping at the
#! first error, which `error` then gives.
#!
#! A reader views the text it reads, which must outlive it. A token's text and an
#! attribute's value view that text where they needed no decoding, and the
#! reader's own memory where they did, which the next token uses again, so what
#! a token gives is good only until the next. The names of elements and
#! attributes, and what the document type declares, view the text, or what the
#! reader holds as long as it lives.
pub struct reader {
var _source: strview; #! The document's text.
var _text: strview; #! The text being read: the document's, or an entity's.
var _at: u64;
var _inputs: vector<input>; #! The texts gone into others from, the document's first.
var _opened: vector<opened>;
var _state: reading;
var _given: options;
var _open: vector<open_element>;
var _attributes: vector<attribute>; #! The last start tag's.
var _spans: vector<value_span>;
var _values: string; #! The values of the last start tag's attributes that were decoded.
var _decoded: string; #! The last token's text, where it was decoded.
var _bindings: vector<binding>;
var _uris: string; #! The names of the namespaces bound.
var _seen: dict<strview, u32>; #! The names of a tag's attributes, where it gives many.
var _keys: string;
var _general: dict<strview, entity>;
var _parameters: dict<strview, entity>;
var _texts: vector<string>; #! Entities' texts and attributes' defaults, each where it stays.
var _declared: vector<declared>;
var _lists: dict<strview, u32>; #! The first attribute declared for each element.
var _skipping: bool; #! Whether declarations are left out, after an entity not read.
var _typed: bool; #! Whether the document type has been read.
var _expanded: u64; #! How many bytes of entities' texts have been read.
var _queued: bool; #! Whether an empty element's end is given next.
var _pending: bool; #! Whether the element the last token ended is let go before the next.
var _bad: maybe<disallowed>;
var _version: strview;
var _encoding: strview;
var _standalone: bool;
var _doctype: strview;
var _error: maybe<error>;
}
#! Makes a reader of XML text.
#! @param text The text to read, which must outlive the reader.
#! @param given How the text is read, and how far reading may go.
#! @returns The reader, at the start of the text.
pub def reader::new(text: strview, given: options = options {}): reader {
var made := reader {
_source = text,
_text = text,
_inputs = vector::<input>::new(),
_opened = vector::<opened>::new(),
_given = given,
_open = vector::<open_element>::new(),
_attributes = vector::<attribute>::new(),
_spans = vector::<value_span>::new(),
_values = string::new(nothing {}),
_decoded = string::new(nothing {}),
_bindings = vector::<binding>::new(),
_uris = string::new(nothing {}),
_seen = dict::<strview, u32>::new(),
_keys = string::new(nothing {}),
_general = dict::<strview, entity>::new(),
_parameters = dict::<strview, entity>::new(),
_texts = vector::<string>::new(),
_declared = vector::<declared>::new(),
_lists = dict::<strview, u32>::new()
};
if text.length > 0xFFFFFFFFu {
made._error = error { kind = error_kind::too_long };
made._state = reading::failed;
return made;
}
made._bad = first_disallowed(text);
return made;
}
#! Why reading stopped before the end of the text, where it did.
#! @param this The reader to ask.
#! @returns The error, or `nothing` where none has been met.
pub val reader::error: maybe<error> {
get => this._error;
}
#! How many elements are open: those whose start tags have been given, and
#! whose ends have not.
#! @param this The reader to ask.
#! @returns The count.
pub val reader::depth: u64 {
get => this._pending ? this._open.length - 1 : this._open.length;
}
#! The attributes of the element whose start tag was given last, those the tag
#! gives first, in its order, then the document type's defaults for those it
#! does not.
#! @param this The reader to ask.
#! @returns A view of them, good until the next token.
pub val reader::attributes: span<attribute> {
get => this._attributes.span;
}
#! The version the XML declaration gives, as `1.0`.
#! @param this The reader to ask.
#! @returns The version, or empty where the text has no declaration, or it has
#! not been read yet.
pub val reader::version: strview {
get => this._version;
}
#! The encoding the XML declaration names, as `UTF-8`.
#! @param this The reader to ask.
#! @returns The encoding as written, or empty where none is named.
pub val reader::encoding: strview {
get => this._encoding;
}
#! Whether the XML declaration says the document stands alone, so nothing
#! outside it declares what it refers to.
#! @param this The reader to ask.
#! @returns Whether it says `standalone="yes"`.
pub val reader::standalone: bool {
get => this._standalone;
}
#! The name the document type gives the root element.
#! @param this The reader to ask.
#! @returns The name, or empty where the text has no document type, or it has
#! not been read yet.
pub val reader::doctype: strview {
get => this._doctype;
}
#! Reads the next token.
#! @param this The reader to read with.
#! @returns The token, or `nothing` at the end of the text or at an error, which
#! `error` tells apart.
pub def reader::next(&mut this): maybe<token> {
if this._state == reading::failed || this._state == reading::done {
return nothing {};
}
if this._pending {
this._pending = false;
this.let_go();
}
if this._queued {
this._queued = false;
return this.close_element(this._open.last.offset);
}
while true {
match this._state {
start => {
if !this.read_declaration() {
return nothing {};
}
this._state = reading::prolog;
}
prolog => {
this.skip_space();
if this.at_end() {
return this.fail(error_kind::no_root, this._at);
}
if this.peek() != '<' {
return this.fail(error_kind::text_outside_root, this._at);
}
if this.looking_at("<?") {
return this.read_instruction();
}
if this.looking_at("<!--") {
return this.read_comment();
}
if this.looking_at("<!DOCTYPE") && !this._typed {
if !this.read_doctype() {
return nothing {};
}
continue;
}
if this.looking_at("<!") || this.looking_at("</") {
return this.fail(error_kind::unexpected_byte, this._at);
}
this._state = reading::content;
return this.read_start();
}
content => {
if this.at_end() {
if this._inputs.empty {
return this.fail(error_kind::unexpected_end, this._at);
}
if !this.leave() {
return nothing {};
}
continue;
}
if this.peek() != '<' {
val read := this.read_text() else { return nothing {}; };
if read.text.length == 0 {
continue;
}
return read;
}
if this.looking_at("</") {
return this.read_end();
}
if this.looking_at("<!--") {
return this.read_comment();
}
if this.looking_at("<![CDATA[") {
return this.read_cdata();
}
if this.looking_at("<?") {
return this.read_instruction();
}
if this.looking_at("<!") {
return this.fail(error_kind::unexpected_byte, this._at);
}
return this.read_start();
}
epilog => {
this.skip_space();
if this.at_end() {
this._state = reading::done;
return nothing {};
}
if this.peek() != '<' {
return this.fail(error_kind::text_outside_root, this._at);
}
if this.looking_at("<?") {
return this.read_instruction();
}
if this.looking_at("<!--") {
return this.read_comment();
}
if name_end(this._text, this._at + 1) != this._at + 1 {
return this.fail(error_kind::second_root, this._at);
}
return this.fail(error_kind::unexpected_byte, this._at);
}
done, failed => return nothing {};
}
}
return nothing {};
}
#! Reads past the rest of the element whose start tag was given last, through
#! its end, as one whose content is not wanted.
#! @param this The reader to read with.
#! @returns Whether the element was read past, which it is not at an error.
pub def reader::skip(&mut this): bool {
var depth: u64 = 1;
while this.next() is some(read) {
if read.kind == token_kind::start {
depth++;
} else if read.kind == token_kind::end {
depth--;
if depth == 0 {
return true;
}
}
}
return false;
}
# Reads the XML declaration, where the text begins with one, after a byte order
# mark, then stops at any byte of the text that breaks UTF-8 or XML's characters.
def reader::read_declaration(&mut this): bool {
val text := this._source;
if text.length >= 2 && ((text[0] == 0xFE && text[1] == 0xFF) || (text[0] == 0xFF && text[1] == 0xFE)) {
return this.stop(error_kind::unsupported_encoding, 0);
}
if text.substr(0, 3) == "\xEF\xBB\xBF" {
this._at = 3;
}
# `<?xml-stylesheet` is an instruction of its own, and `<?xml?>` a declaration
# without its version.
val after := this._at + 5;
if this.looking_at("<?xml") && after < text.length && (is_space(text[after]) || text[after] == '?') {
this._at = after;
if !this.skip_space() || !this.take("version") {
return this.stop(error_kind::invalid_declaration, this._at);
}
val version := this.read_pseudo_value() else { return false; };
if version.length < 3 || !version.starts_with("1.") || digits_end(version, 2) != version.length {
return this.stop(error_kind::invalid_declaration, this._at);
}
this._version = version;
var spaced := this.skip_space();
if this.looking_at("encoding") {
if !spaced {
return this.stop(error_kind::invalid_declaration, this._at);
}
this._at += 8;
val encoding := this.read_pseudo_value() else { return false; };
if !is_encoding_name(encoding) {
return this.stop(error_kind::invalid_declaration, this._at);
}
this._encoding = encoding;
spaced = this.skip_space();
}
if this.looking_at("standalone") {
if !spaced {
return this.stop(error_kind::invalid_declaration, this._at);
}
this._at += 10;
val standalone := this.read_pseudo_value() else { return false; };
if standalone != "yes" && standalone != "no" {
return this.stop(error_kind::invalid_declaration, this._at);
}
this._standalone = standalone == "yes";
this.skip_space();
}
if !this.take("?>") {
return this.stop(error_kind::invalid_declaration, this._at);
}
}
# Text declared in another encoding is read while it is ASCII, which it then
# is the same as UTF-8, and stops at the first byte past.
if this._bad is some(bad) {
var kind := bad.kind;
if kind == error_kind::invalid_utf8 && this._encoding.length != 0 && !same_letters(this._encoding, "UTF-8") {
kind = error_kind::unsupported_encoding;
}
return this.stop(kind, bad.offset);
}
return true;
}
# Reads `=` and a quoted value after one of the declaration's names.
def reader::read_pseudo_value(&mut this): maybe<strview> {
this.skip_space();
if !this.take("=") {
_ = this.stop(error_kind::invalid_declaration, this._at);
return nothing {};
}
this.skip_space();
val quote := this.peek();
if quote != '"' && quote != '\'' {
_ = this.stop(error_kind::invalid_declaration, this._at);
return nothing {};
}
val start := this._at + 1;
var end := start;
while end < this._text.length && this._text[end] != quote {
end++;
}
if end >= this._text.length {
_ = this.stop(error_kind::invalid_declaration, this._at);
return nothing {};
}
this._at = end + 1;
return this._text.substr(start, end - start);
}
# Reads the document type: the root element's name, where its declarations
# outside the document are, which are not read, and its internal subset.
def reader::read_doctype(&mut this): bool {
this._at += 9;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
this._doctype = this.read_name() else { return false; };
this._typed = true;
val spaced := this.skip_space();
if this.looking_at("SYSTEM") || this.looking_at("PUBLIC") {
if !spaced {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.read_external_id(false) {
return false;
}
this.skip_space();
}
if this.peek() == '[' {
this._at++;
if !this.read_internal_subset() {
return false;
}
this._at++;
this.skip_space();
}
return this.expect('>');
}
# Reads the internal subset's declarations, up to the `]` ending it, which is
# left to read.
def reader::read_internal_subset(&mut this): bool {
while true {
this.skip_space();
if this.at_end() {
if this._inputs.empty {
return this.stop(error_kind::unexpected_end, this._at);
}
if !this.leave() {
return false;
}
continue;
}
val byte := this.peek();
if byte == ']' {
# The subset ends in the document, not within a parameter entity's text.
if !this._inputs.empty {
return this.stop(error_kind::unexpected_byte, this._at);
}
return true;
}
if byte == '%' {
if !this.enter_parameter() {
return false;
}
continue;
}
var read := false;
if this.looking_at("<!ENTITY") {
read = this.read_entity_declaration();
} else if this.looking_at("<!ATTLIST") {
read = this.read_attribute_list();
} else if this.looking_at("<!ELEMENT") {
read = this.read_element_declaration();
} else if this.looking_at("<!NOTATION") {
read = this.read_notation();
} else if this.looking_at("<?") {
read = this.read_instruction() is some(_);
} else if this.looking_at("<!--") {
read = this.read_comment() is some(_);
} else {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !read {
return false;
}
}
return true;
}
# Goes into a parameter entity's text, between declarations, from its reference.
def reader::enter_parameter(&mut this): bool {
val start := this._at;
val end := name_end(this._text, start + 1);
if end == start + 1 || end >= this._text.length || this._text[end] != ';' {
return this.stop(error_kind::invalid_reference, start);
}
val name := this._text.substr(start + 1, end - start - 1);
this._at = end + 1;
# An entity not read may declare again what the declarations after it do, which
# are then left out, unless the document stands alone, so declares all it uses.
val found := this._parameters.get(&name) else {
if this._standalone {
return this.stop(error_kind::undeclared_entity, start);
}
this._skipping = true;
return true;
};
if found.external {
this._skipping = this._skipping || !this._standalone;
return true;
}
return this.enter(found, true, start, this._at);
}
# Reads an entity's declaration, which binds its name where it is the first of
# the name.
def reader::read_entity_declaration(&mut this): bool {
this._at += 8;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
var parameter := false;
if this.peek() == '%' {
this._at++;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
parameter = true;
}
val at := this._at;
val name := this.read_name() else { return false; };
if this._given.namespaces && name.find(":") is some(_) {
return this.stop(error_kind::invalid_name, at);
}
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
var made := entity { name = name };
var value := string::new(nothing {});
val quote := this.peek();
if quote == '"' || quote == '\'' {
if !this.read_entity_value(&mut value) {
return false;
}
this.skip_space();
} else {
if !this.read_external_id(false) {
return false;
}
made.external = true;
val spaced := this.skip_space();
if this.looking_at("NDATA") {
if parameter || !spaced {
return this.stop(error_kind::unexpected_byte, this._at);
}
this._at += 5;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
_ = this.read_name() else { return false; };
made.unparsed = true;
this.skip_space();
}
}
if !this.expect('>') {
return false;
}
# The entities XML gives are its own, however declared again.
if this._skipping || (!parameter && predefined(name) is some(_)) {
return true;
}
if (parameter && this._parameters.contains(&name)) || (!parameter && this._general.contains(&name)) {
return true;
}
if !made.external {
this._texts.append(move(value));
made.text = this._texts.last.span;
}
if parameter {
_ = this._parameters.insert(name, made);
} else {
_ = this._general.insert(name, made);
}
return true;
}
# Reads an entity's value from its opening quote into its replacement text:
# character references are replaced, and references to entities kept as they are
# written, to be replaced where the entity is used.
def reader::read_entity_value(&mut this, into: &mut string): bool {
val quote := this.peek();
this._at++;
while true {
if this.at_end() {
return this.stop(error_kind::unexpected_end, this._at);
}
val byte := this._text[this._at];
if byte == quote {
this._at++;
return true;
}
if byte == '%' {
# A parameter entity is referred to only between declarations in the
# internal subset.
return this.stop(error_kind::unexpected_byte, this._at);
}
if byte == '&' {
val read := this.read_reference() else { return false; };
if read.name.length == 0 {
append_utf8(read.code, into);
} else {
into.append(this._text.substr(this._at, read.end - this._at));
}
this._at = read.end;
continue;
}
if byte == '\r' && this._inputs.empty {
into.push('\n');
this._at++;
if this.peek() == '\n' {
this._at++;
}
continue;
}
into.push(byte);
this._at++;
}
return true;
}
# Reads `SYSTEM` and where the text is, or `PUBLIC`, its public name, and where
# it is, which a notation may leave out.
def reader::read_external_id(&mut this, notation: bool): bool {
if this.take("SYSTEM") {
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
return this.read_literal(false);
}
if !this.take("PUBLIC") {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.read_literal(true) {
return false;
}
val spaced := this.skip_space();
val quote := this.peek();
if notation && quote != '"' && quote != '\'' {
return true;
}
if !spaced {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
return this.read_literal(false);
}
# Reads a quoted system literal, or a public name, which holds only the bytes
# `PubidChar` allows.
def reader::read_literal(&mut this, public: bool): bool {
val quote := this.peek();
if quote != '"' && quote != '\'' {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
this._at++;
while true {
if this.at_end() {
return this.stop(error_kind::unexpected_end, this._at);
}
val byte := this._text[this._at];
if byte == quote {
this._at++;
return true;
}
if public && !is_public_char(byte) {
return this.stop(error_kind::unexpected_byte, this._at);
}
this._at++;
}
return true;
}
# Reads an attribute-list declaration: each attribute's name, type, and default.
def reader::read_attribute_list(&mut this): bool {
this._at += 9;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
val element := this.read_name() else { return false; };
while true {
val spaced := this.skip_space();
if this.peek() == '>' {
this._at++;
return true;
}
if !spaced {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
val name := this.read_name() else { return false; };
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
# The type: CDATA, a tokenized type, a notation's names, or names to choose from.
var cdata := false;
if this.peek() == '(' {
if !this.read_enumeration(false) {
return false;
}
} else {
val at := this._at;
val type_name := this.read_name() else { return false; };
if type_name == "CDATA" {
cdata = true;
} else if type_name == "NOTATION" {
if !this.skip_space() || this.peek() != '(' {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.read_enumeration(true) {
return false;
}
} else if type_name != "ID" && type_name != "IDREF" && type_name != "IDREFS" && type_name != "ENTITY"
&& type_name != "ENTITIES" && type_name != "NMTOKEN" && type_name != "NMTOKENS" {
return this.stop(error_kind::unexpected_byte, at);
}
}
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
# The default: none, as `#REQUIRED` and `#IMPLIED` say, or a value, which
# `#FIXED` may come before.
var value: maybe<strview> = nothing {};
var fixed := true;
if this.peek() == '#' {
val at := this._at;
this._at++;
val word := this.read_name() else { return false; };
if word == "FIXED" {
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
} else if word == "REQUIRED" || word == "IMPLIED" {
fixed = false;
} else {
return this.stop(error_kind::unexpected_byte, at);
}
}
if fixed {
val read := this.read_default(cdata) else { return false; };
value = read;
}
this.declare(element, name, cdata, value);
}
return true;
}
# Reads names, or name tokens, between `(` and `)`, each after a `|`.
def reader::read_enumeration(&mut this, notation: bool): bool {
this._at++;
while true {
this.skip_space();
val at := this._at;
val end := notation ? name_end(this._text, at) : name_chars_end(this._text, at);
if end == at {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, at);
}
this._at = end;
this.skip_space();
if this.peek() != '|' {
return this.expect(')');
}
this._at++;
}
return true;
}
# Reads an attribute's default value, normalized as its values are, and keeps it
# where it stays as long as the reader.
def reader::read_default(&mut this, cdata: bool): maybe<strview> {
this._values.clear();
var span := this.read_value() else { return nothing {}; };
if !cdata {
val plain: strview = span.decoded ? "" : this._text.substr(span.start, span.length);
span = this.collapsed(plain, span);
}
if !span.decoded {
return this._text.substr(span.start, span.length);
}
this._texts.append(string::from(this._values.substr(span.start, span.length), nothing {}));
return this._texts.last.span;
}
# Declares an attribute of an element, unless one of the name is already
# declared, since the first declaration binds.
def reader::declare(&mut this, element: strview, name: strview, cdata: bool, value: maybe<strview>): void {
if this._skipping {
return;
}
var last := no_index;
if this._lists.get(&element) is some(first) {
var at: u32 = first;
while at != no_index {
if this._declared[at as u64].name == name {
return;
}
last = at;
at = this._declared[at as u64].next;
}
}
val index := this._declared.length as u32;
this._declared.append(declared { name = name, cdata = cdata, value = value, next = no_index });
if last == no_index {
_ = this._lists.insert(element, index);
} else {
this._declared[last as u64].next = index;
}
}
# Reads an element's declaration, checking its content model's grammar.
def reader::read_element_declaration(&mut this): bool {
this._at += 9;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
_ = this.read_name() else { return false; };
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.take("EMPTY") && !this.take("ANY") {
if this.peek() != '(' {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
this._at++;
this.skip_space();
if this.take("#PCDATA") {
if !this.read_mixed() {
return false;
}
} else if !this.read_group(1) {
return false;
}
}
this.skip_space();
return this.expect('>');
}
# Reads the rest of mixed content, after `(#PCDATA`: `)`, or `)*`, or the names
# of the elements it may hold, each after a `|`, and `)*`.
def reader::read_mixed(&mut this): bool {
this.skip_space();
if this.peek() == ')' {
this._at++;
_ = this.take("*");
return true;
}
while this.peek() == '|' {
this._at++;
this.skip_space();
_ = this.read_name() else { return false; };
this.skip_space();
}
return this.expect(')') && this.expect('*');
}
# Reads a choice or sequence of content particles after its `(`, each a name or
# a group, all after the first after the same `|` or `,`, and how often each may
# stand.
def reader::read_group(&mut this, depth: u32): bool {
if depth >= this._given.depth {
return this.stop(error_kind::too_deep, this._at);
}
var separator: u8 = 0;
while true {
if this.peek() == '(' {
this._at++;
this.skip_space();
if !this.read_group(depth + 1) {
return false;
}
} else {
_ = this.read_name() else { return false; };
this.take_quantifier();
}
this.skip_space();
val byte := this.peek();
if byte == ')' {
this._at++;
this.take_quantifier();
return true;
}
if (byte != '|' && byte != ',') || (separator != 0 && byte != separator) {
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
separator = byte;
this._at++;
this.skip_space();
}
return true;
}
# Moves past how often a content particle may stand: `?`, `*`, or `+`.
def reader::take_quantifier(&mut this): void {
val byte := this.peek();
if byte == '?' || byte == '*' || byte == '+' {
this._at++;
}
}
# Reads a notation's declaration.
def reader::read_notation(&mut this): bool {
this._at += 10;
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
val at := this._at;
val name := this.read_name() else { return false; };
if this._given.namespaces && name.find(":") is some(_) {
return this.stop(error_kind::invalid_name, at);
}
if !this.skip_space() {
return this.stop(error_kind::unexpected_byte, this._at);
}
if !this.read_external_id(true) {
return false;
}
this.skip_space();
return this.expect('>');
}
# Reads a start tag, or an empty element's tag, and its attributes: those it
# gives, then the defaults of those it doesn't, then the namespaces they bind.
def reader::read_start(&mut this): maybe<token> {
val start := this._at;
this._at++;
val name := this.read_name() else { return nothing {}; };
this._attributes.clear();
this._spans.clear();
this._values.clear();
var empty := false;
while true {
val spaced := this.skip_space();
if this.at_end() {
return this.fail(error_kind::unexpected_end, this._at);
}
val byte := this.peek();
if byte == '>' {
this._at++;
break;
}
if byte == '/' {
this._at++;
if !this.expect('>') {
return nothing {};
}
empty = true;
break;
}
if !spaced {
return this.fail(error_kind::unexpected_byte, this._at);
}
val at := this._at;
val named := this.read_name() else { return nothing {}; };
this.skip_space();
if !this.expect('=') {
return nothing {};
}
this.skip_space();
val span := this.read_value() else { return nothing {}; };
if this.given_before(named) {
return this.fail(error_kind::repeated_attribute, at);
}
val plain: strview = span.decoded ? "" : this._text.substr(span.start, span.length);
this._attributes.append(attribute { name = named, local = named, value = plain, specified = true, offset = this.here(at) });
this._spans.append(span);
}
if this._open.length >= this._given.depth as u64 {
return this.fail(error_kind::too_deep, start);
}
this.add_defaults(name, this.here(start));
# `_values` is whole now, so what was decoded into it is viewed.
for index in 0..this._spans.length {
val span := this._spans[index];
if span.decoded {
this._attributes[index].value = this._values.substr(span.start, span.length);
}
}
var prefix: strview = "";
var local: strview = name;
var namespace: strview = "";
val bindings := this._bindings.length;
val uris := this._uris.length;
if this._given.namespaces {
if !this.bind() || !this.resolve_attributes() {
return nothing {};
}
if name.find(":") is some(colon) {
if !is_qualified(name) {
return this.fail(error_kind::invalid_name, start + 1);
}
prefix = name.substr(0, colon);
local = name.substr(colon + 1, name.length - colon - 1);
if prefix == "xmlns" {
return this.fail(error_kind::invalid_namespace, start + 1);
}
}
namespace = this.lookup(prefix) else { return this.fail(error_kind::unbound_prefix, start + 1); };
}
this._open.append(open_element {
name = name,
prefix = prefix,
local = local,
level = this._inputs.length,
bindings = bindings,
uris = uris,
offset = this.here(start)
});
this._queued = empty;
return token {
kind = token_kind::start,
empty = empty,
name = name,
prefix = prefix,
local = local,
namespace = namespace,
offset = this.here(start)
};
}
# Whether the tag being read gives an attribute of a name already: found one by
# one among a few, and by a table among many.
def reader::given_before(&mut this, name: strview): bool {
val count := this._attributes.length;
if count < 8 {
for index in 0..count {
if this._attributes[index].name == name {
return true;
}
}
return false;
}
if count == 8 {
this._seen.clear();
for index in 0..count {
val held := this._attributes[index].name;
_ = this._seen.insert(held, index as u32);
}
}
return !this._seen.insert(name, count as u32);
}
# Adds the defaults the document type declares for an element's attributes it
# does not give, and collapses the spaces of those it gives of types other than
# CDATA.
def reader::add_defaults(&mut this, element: strview, tag: u64): void {
var at: u32 = this._lists.get(&element) else { return; };
while at != no_index {
val held := this._declared[at as u64];
at = held.next;
var given := false;
for index in 0..this._attributes.length {
if this._attributes[index].name == held.name {
given = true;
if !held.cdata {
val value := this._attributes[index].value;
val span := this._spans[index];
this._spans[index] = this.collapsed(value, span);
}
break;
}
}
if !given && held.value is some(value) {
this._attributes.append(attribute { name = held.name, local = held.name, value = value, offset = tag });
this._spans.append(value_span {});
}
}
}
# Collapses the spaces of a value, as an attribute of a type other than CDATA
# has them: none at either end, and one between words. One decoded already is
# collapsed in place, and one in the text read is copied first, where it needs it.
def reader::collapsed(&mut this, value: strview, span: value_span): value_span {
if span.decoded {
return value_span { start = span.start, length = collapse_in(&mut this._values, span.start, span.length), decoded = true };
}
if !needs_collapse(value) {
return span;
}
val start := this._values.length;
this._values.append(value);
return value_span { start = start, length = collapse_in(&mut this._values, start, value.length), decoded = true };
}
# Binds the namespaces the tag's attributes declare, checking each as Namespaces
# in XML does: `xml` is bound only to its own, `xmlns` never, and a prefix never
# to none.
def reader::bind(&mut this): bool {
for index in 0..this._attributes.length {
val held := this._attributes[index];
var prefix: strview = "";
if held.name == "xmlns" {
if held.value == xml_namespace || held.value == xmlns_namespace {
return this.stop(error_kind::invalid_namespace, held.offset);
}
} else if held.name.starts_with("xmlns:") {
prefix = held.name.substr(6, held.name.length - 6);
if prefix.length == 0 || prefix.find(":") is some(_) || !is_name_start(code_at(prefix, 0)) {
return this.stop(error_kind::invalid_name, held.offset);
}
if prefix == "xml" {
if held.value != xml_namespace {
return this.stop(error_kind::invalid_namespace, held.offset);
}
continue;
}
if prefix == "xmlns" || held.value.length == 0 || held.value == xml_namespace || held.value == xmlns_namespace {
return this.stop(error_kind::invalid_namespace, held.offset);
}
} else {
continue;
}
val start := this._uris.length;
this._uris.append(held.value);
this._bindings.append(binding { prefix = prefix, start = start, length = held.value.length });
}
return true;
}
# Splits each attribute's name into its prefix and local name, and finds the
# namespace each is in, then checks no two are the same name in namespaces.
def reader::resolve_attributes(&mut this): bool {
for index in 0..this._attributes.length {
val held := this._attributes[index];
if held.name == "xmlns" {
this._attributes[index].namespace = xmlns_namespace;
continue;
}
val colon := held.name.find(":") else { continue; };
if !is_qualified(held.name) {
return this.stop(error_kind::invalid_name, held.offset);
}
val prefix := held.name.substr(0, colon);
var namespace: strview = xmlns_namespace;
if prefix != "xmlns" {
namespace = this.lookup(prefix) else { return this.stop(error_kind::unbound_prefix, held.offset); };
}
this._attributes[index].prefix = prefix;
this._attributes[index].local = held.name.substr(colon + 1, held.name.length - colon - 1);
this._attributes[index].namespace = namespace;
}
if this.repeated_in_namespaces() is some(index) {
return this.stop(error_kind::repeated_attribute, this._attributes[index].offset);
}
return true;
}
# The first attribute whose namespace and local name one before it has, which
# two prefixes bound to one namespace give: found one by one among a few, and by
# a table among many.
def reader::repeated_in_namespaces(&mut this): maybe<u64> {
val count := this._attributes.length;
if count < 2 {
return nothing {};
}
if count <= 8 {
for index in 1..count {
val held := this._attributes[index];
if held.namespace.length == 0 {
continue;
}
for before in 0..index {
val other := this._attributes[before];
if other.namespace == held.namespace && other.local == held.local {
return index;
}
}
}
return nothing {};
}
# Each is found by its namespace and local name as one key, which no name
# nor namespace holds the zero byte of.
this._keys.clear();
for index in 0..count {
val held := this._attributes[index];
this._keys.append(held.namespace);
this._keys.push(0);
this._keys.append(held.local);
}
this._seen.clear();
var at: u64 = 0;
for index in 0..count {
val held := this._attributes[index];
val length := held.namespace.length + 1 + held.local.length;
if held.namespace.length != 0 && !this._seen.insert(this._keys.substr(at, length), index as u32) {
return index;
}
at += length;
}
return nothing {};
}
# The namespace a prefix is bound to, the innermost binding first.
def reader::lookup(&this, prefix: strview): maybe<strview> {
if prefix == "xml" {
return xml_namespace;
}
var at := this._bindings.length;
while at > 0 {
at--;
val held := this._bindings[at];
if held.prefix == prefix {
return this._uris.substr(held.start, held.length);
}
}
if prefix.length == 0 {
return "";
}
return nothing {};
}
# Reads an end tag, which must name the element open, and be in the same text.
def reader::read_end(&mut this): maybe<token> {
val start := this._at;
this._at += 2;
val name := this.read_name() else { return nothing {}; };
this.skip_space();
if !this.expect('>') {
return nothing {};
}
val open := this._open.last;
if open.name != name {
return this.fail(error_kind::mismatched_tag, start);
}
if open.level != this._inputs.length {
return this.fail(error_kind::unbalanced_entity, start);
}
return this.close_element(this.here(start));
}
# The end of the element open, which is let go before the next token, so the
# namespaces it binds name it until then.
def reader::close_element(&mut this, offset: u64): maybe<token> {
val open := this._open.last;
var namespace: strview = "";
if this._given.namespaces {
namespace = this.lookup(open.prefix) else "";
}
this._pending = true;
return token {
kind = token_kind::end,
name = open.name,
prefix = open.prefix,
local = open.local,
namespace = namespace,
offset = offset
};
}
# Lets go of the element whose end was given last, and of the namespaces it
# bound.
def reader::let_go(&mut this): void {
val open := this._open.last;
this._bindings.resize(open.bindings);
this._uris.resize(open.uris);
this._open.truncate();
if this._open.empty {
this._state = reading::epilog;
}
}
# Reads character data, up to markup or the end of the text, replacing
# references and making line breaks `\n`. An entity's text is read where it is
# referred to, going on past its end in the text referring to it.
def reader::read_text(&mut this): maybe<token> {
val offset := this.here(this._at);
this._decoded.clear();
var decoded := false;
var run := this._at;
while true {
if this.at_end() {
if this._inputs.empty {
break;
}
this._decoded.append(this._text.substr(run, this._at - run));
decoded = true;
if !this.leave() {
return nothing {};
}
run = this._at;
continue;
}
val byte := this._text[this._at];
if byte == '<' {
break;
}
if byte == '&' || (byte == '\r' && this._inputs.empty) {
this._decoded.append(this._text.substr(run, this._at - run));
decoded = true;
if byte == '\r' {
this._decoded.push('\n');
this._at++;
if this.peek() == '\n' {
this._at++;
}
} else if !this.enter_reference() {
return nothing {};
}
run = this._at;
continue;
}
if byte == ']' && this.looking_at("]]>") {
return this.fail(error_kind::unexpected_byte, this._at);
}
this._at++;
}
var text := this._text.substr(run, this._at - run);
if decoded {
this._decoded.append(text);
text = this._decoded.span;
}
return token { kind = token_kind::text, text = text, offset = offset };
}
# Replaces a reference within text: a character's or one of XML's own entities'
# with what it stands for, and another entity's by going into its text.
def reader::enter_reference(&mut this): bool {
val start := this._at;
val read := this.read_reference() else { return false; };
if read.name.length == 0 {
append_utf8(read.code, &mut this._decoded);
this._at = read.end;
return true;
}
if predefined(read.name) is some(byte) {
this._decoded.push(byte);
this._at = read.end;
return true;
}
val found := this._general.get(&read.name) else { return this.stop(error_kind::undeclared_entity, start); };
return this.enter(found, false, start, read.end);
}
# Goes into an entity's text from a reference to it, reading on after the
# reference once the text ends.
def reader::enter(&mut this, found: entity, parameter: bool, reference: u64, after: u64): bool {
if found.external || found.unparsed {
return this.stop(error_kind::external_entity, reference);
}
if !this.open_entity(found.name, parameter, found.text.length, reference) {
return false;
}
this._inputs.append(input { text = this._text, at = after, reference = reference });
this._text = found.text;
this._at = 0;
return true;
}
# Goes back from an entity's text, at its end, to the text referring to it. The
# entity must have ended each element it began.
def reader::leave(&mut this): bool {
if !this._open.empty && this._open.last.level == this._inputs.length {
return this.stop(error_kind::unbalanced_entity, this._at);
}
val back := this._inputs.last;
this._text = back.text;
this._at = back.at;
this._inputs.truncate();
this._opened.truncate();
return true;
}
# Opens an entity whose text is about to be read, counting its text against the
# limit, unless it is open already, which would never end.
def reader::open_entity(&mut this, name: strview, parameter: bool, length: u64, reference: u64): bool {
for index in 0..this._opened.length {
val held := this._opened[index];
if held.parameter == parameter && held.name == name {
return this.stop(error_kind::recursive_entity, reference);
}
}
if this._opened.length >= this._given.depth as u64 {
return this.stop(error_kind::too_deep, reference);
}
this._expanded += length;
if this._expanded > this._given.expansion {
return this.stop(error_kind::too_much_expansion, reference);
}
this._opened.append(opened { name = name, parameter = parameter });
return true;
}
# Reads an attribute's value from its opening quote, normalizing it as XML does:
# each whitespace character becomes a space, and references are replaced, an
# entity's text normalized the same way. Where nothing needed it, the value is
# left where it is in the text.
def reader::read_value(&mut this): maybe<value_span> {
val quote := this.peek();
if quote != '"' && quote != '\'' {
_ = this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
return nothing {};
}
this._at++;
val begin := this._at;
val start := this._values.length;
var run := begin;
var decoded := false;
while true {
if this.at_end() {
_ = this.stop(error_kind::unexpected_end, this._at);
return nothing {};
}
val byte := this._text[this._at];
if byte == quote {
break;
}
if byte == '<' {
_ = this.stop(error_kind::unexpected_byte, this._at);
return nothing {};
}
if byte == '&' || byte == '\t' || byte == '\n' || byte == '\r' {
this._values.append(this._text.substr(run, this._at - run));
decoded = true;
if byte == '&' {
if !this.add_reference() {
return nothing {};
}
} else {
# A line break of the document's own is one, however it is written.
this._values.push(' ');
this._at++;
if byte == '\r' && this._inputs.empty && this.peek() == '\n' {
this._at++;
}
}
run = this._at;
continue;
}
this._at++;
}
val end := this._at;
this._at++;
if !decoded {
return value_span { start = begin, length = end - begin };
}
this._values.append(this._text.substr(run, end - run));
return value_span { start = start, length = this._values.length - start, decoded = true };
}
# Replaces a reference within an attribute's value with what it stands for.
def reader::add_reference(&mut this): bool {
val start := this._at;
val read := this.read_reference() else { return false; };
this._at = read.end;
if read.name.length == 0 {
append_utf8(read.code, &mut this._values);
return true;
}
if predefined(read.name) is some(byte) {
this._values.push(byte);
return true;
}
val found := this._general.get(&read.name) else { return this.stop(error_kind::undeclared_entity, start); };
return this.expand_value(found, start);
}
# Appends what an entity's text stands for within an attribute's value,
# normalized, which must hold no `<`, nor refer to an entity outside the text.
def reader::expand_value(&mut this, found: entity, reference: u64): bool {
if found.external || found.unparsed {
return this.stop(error_kind::external_entity, reference);
}
if !this.open_entity(found.name, false, found.text.length, reference) {
return false;
}
val text := found.text;
var at: u64 = 0;
while at < text.length {
val byte := text[at];
if byte == '<' {
return this.stop(error_kind::unexpected_byte, reference);
}
if byte == '&' {
val read := reference_at(text, at) else (kind) { return this.stop(kind, reference); };
at = read.end;
if read.name.length == 0 {
append_utf8(read.code, &mut this._values);
} else if predefined(read.name) is some(single) {
this._values.push(single);
} else {
val inner := this._general.get(&read.name) else { return this.stop(error_kind::undeclared_entity, reference); };
if !this.expand_value(inner, reference) {
return false;
}
}
continue;
}
this._values.push(is_space(byte) ? ' ' : byte);
at++;
}
this._opened.truncate();
return true;
}
# Reads the reference at an `&`, without moving past it.
def reader::read_reference(&mut this): maybe<referral> {
match reference_at(this._text, this._at) {
value(read) => return read;
error(kind) => {
_ = this.stop(kind, this._at);
return nothing {};
}
}
return nothing {};
}
# Reads a comment, whose text must hold no `--`.
def reader::read_comment(&mut this): maybe<token> {
val start := this._at;
val from := start + 4;
val found := this._text.substr(from, this._text.length - from).find("--") else {
return this.fail(error_kind::unexpected_end, this._text.length);
};
val end := from + found;
if end + 2 >= this._text.length {
return this.fail(error_kind::unexpected_end, this._text.length);
}
if this._text[end + 2] != '>' {
return this.fail(error_kind::unexpected_byte, end);
}
this._at = end + 3;
return token { kind = token_kind::comment, text = this.normalized(from, end), offset = this.here(start) };
}
# Reads a processing instruction: its target, which is no `xml` of any case, and
# what follows, after whitespace.
def reader::read_instruction(&mut this): maybe<token> {
val start := this._at;
this._at += 2;
val target := this.read_name() else { return nothing {}; };
if same_letters(target, "xml") {
return this.fail(error_kind::invalid_declaration, start);
}
if this._given.namespaces && target.find(":") is some(_) {
return this.fail(error_kind::invalid_name, start + 2);
}
var from := this._at;
if !this.looking_at("?>") {
if !this.skip_space() {
return this.fail(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
from = this._at;
}
val found := this._text.substr(from, this._text.length - from).find("?>") else {
return this.fail(error_kind::unexpected_end, this._text.length);
};
this._at = from + found + 2;
return token { kind = token_kind::instruction, name = target, text = this.normalized(from, from + found), offset = this.here(start) };
}
# Reads a CDATA section, whose text is given as it is.
def reader::read_cdata(&mut this): maybe<token> {
val start := this._at;
val from := start + 9;
val found := this._text.substr(from, this._text.length - from).find("]]>") else {
return this.fail(error_kind::unexpected_end, this._text.length);
};
this._at = from + found + 3;
return token { kind = token_kind::text, cdata = true, text = this.normalized(from, from + found), offset = this.here(start) };
}
# Part of the text being read, with the document's line breaks made `\n`. An
# entity's text is given as it is, since a `\r` in it was written as a reference.
def reader::normalized(&mut this, from: u64, to: u64): strview {
val raw := this._text.substr(from, to - from);
if !this._inputs.empty || raw.find("\r") is none {
return raw;
}
this._decoded.clear();
var at: u64 = 0;
while at < raw.length {
val byte := raw[at];
if byte == '\r' {
this._decoded.push('\n');
if at + 1 < raw.length && raw[at + 1] == '\n' {
at++;
}
} else {
this._decoded.push(byte);
}
at++;
}
return this._decoded.span;
}
# Reads a name, or stops where none begins.
def reader::read_name(&mut this): maybe<strview> {
val start := this._at;
val end := name_end(this._text, start);
if end == start {
_ = this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, start);
return nothing {};
}
this._at = end;
return this._text.substr(start, end - start);
}
# Moves past whitespace.
# @returns Whether there was any.
def reader::skip_space(&mut this): bool {
val from := this._at;
while this._at < this._text.length && is_space(this._text[this._at]) {
this._at++;
}
return this._at != from;
}
# Moves past a byte, or stops where another stands there.
def reader::expect(&mut this, byte: u8): bool {
if !this.at_end() && this._text[this._at] == byte {
this._at++;
return true;
}
return this.stop(this.at_end() ? error_kind::unexpected_end : error_kind::unexpected_byte, this._at);
}
# Moves past text where it stands next.
def reader::take(&mut this, word: strview): bool {
if !this.looking_at(word) {
return false;
}
this._at += word.length;
return true;
}
def reader::looking_at(&this, word: strview): bool {
return this._text.substr(this._at, word.length) == word;
}
# The byte the reader is at, or 0 at the end of the text it reads.
def reader::peek(&this): u8 {
return this.at_end() ? 0 : this._text[this._at];
}
def reader::at_end(&this): bool {
return this._at >= this._text.length;
}
# Where in the document something at a byte of the text being read is: there,
# in the document's own text, or where the entity holding it is referred to.
def reader::here(&this, at: u64): u64 {
return this._inputs.empty ? at : this._inputs[0].reference;
}
# Stops at an error, which `error` then gives.
def reader::stop(&mut this, kind: error_kind, at: u64): bool {
this._error = error_at(kind, this._source, this.here(at));
this._state = reading::failed;
return false;
}
def reader::fail(&mut this, kind: error_kind, at: u64): maybe<token> {
_ = this.stop(kind, at);
return nothing {};
}
# The reference beginning at an `&`: `&#` and decimal digits, `&#x` and
# hexadecimal ones, or a name, then `;`.
def reference_at(text: strview, at: u64): result<referral, error_kind> {
if at + 1 < text.length && text[at + 1] == '#' {
var index := at + 2;
var base: u32 = 10;
if index < text.length && text[index] == 'x' {
base = 16;
index++;
}
val digits := index;
var code: u32 = 0;
while index < text.length && text[index].is_base_digit(base as u8) {
# Past the last character there is, it can only be wrong, so it grows no more.
if code <= 0x10FFFF {
code = code * base + text[index].digit_value as u32;
}
index++;
}
if index == digits || index >= text.length || text[index] != ';' {
return error_kind::invalid_reference;
}
if !is_char(code) {
return error_kind::invalid_character;
}
return referral { code = code, end = index + 1 };
}
val end := name_end(text, at + 1);
if end == at + 1 || end >= text.length || text[end] != ';' {
return error_kind::invalid_reference;
}
return referral { name = text.substr(at + 1, end - at - 1), end = end + 1 };
}
# The character one of XML's own entities stands for: `lt`, `gt`, `amp`, `apos`,
# and `quot`.
def predefined(name: strview): maybe<u8> {
val byte: u8 = match name {
"lt" => '<',
"gt" => '>',
"amp" => '&',
"apos" => '\'',
"quot" => '"',
else => 0,
};
return nothing {} if byte == 0;
return byte;
}
# Collapses the spaces of part of a string in place: none at either end, and one
# between words.
# @returns How long the part is after.
def collapse_in(text: &mut string, start: u64, length: u64): u64 {
var to := start;
var spaced := false; # Whether a space goes before the next word.
for at in start..start + length {
val byte := text[at];
if byte == ' ' {
spaced = to != start;
continue;
}
if spaced {
text[to] = ' ';
to++;
spaced = false;
}
text[to] = byte;
to++;
}
return to - start;
}
# Whether collapsing a value's spaces changes it.
def needs_collapse(value: strview): bool {
if value.length == 0 {
return false;
}
return value[0] == ' ' || value[value.length - 1] == ' ' || value.find(" ") is some(_);
}
# Whether a name is an encoding's, `EncName`: a letter, then letters, digits, `.`,
# `_`, and `-`.
def is_encoding_name(name: strview): bool {
if name.length == 0 || !name[0].is_alpha {
return false;
}
for byte in name {
if !byte.is_alnum && byte != '.' && byte != '_' && byte != '-' {
return false;
}
}
return true;
}
# Whether two names are the same but for the case of their ASCII letters.
def same_letters(a: strview, b: strview): bool {
if a.length != b.length {
return false;
}
for index in 0..a.length {
if a[index].to_lower != b[index].to_lower {
return false;
}
}
return true;
}
# Where a run of decimal digits beginning at a byte ends.
def digits_end(text: strview, at: u64): u64 {
var index := at;
while index < text.length && text[index].is_digit {
index++;
}
return index;
}