///|
/// Malformed input; carries a message and the code unit offset where
/// parsing stopped.
#derive(Debug)
pub suberror ParseError {
  ParseError(String, Int32)
}

///|
pub extend ParseError with Debug::{to_repr}

///|
pub impl Show for ParseError with fn output(self, logger) {
  match self {
    ParseError(msg, pos) => logger.write_string("\{msg} at offset \{pos}")
  }
}

///|
pub extend ParseError with Show::{to_string, output}

///|
/// Elements whose text content is significant and must be kept verbatim.
let text_elements : Array[String] = [
  "text", "tspan", "textPath", "tref", "style", "script", "title", "desc", "pre",
]

///|
priv struct Parser {
  text : String
  src : ArrayView[UInt16]
  mut pos : Int32
}

///|
fn Parser::peek(self : Parser, offset~ : Int32 = 0) -> Int32 {
  let i = self.pos + offset
  if i < self.src.length() {
    self.src[i].to_int()
  } else {
    -1
  }
}

///|
fn Parser::eof(self : Parser) -> Bool {
  self.pos >= self.src.length()
}

///|
fn Parser::starts_with(self : Parser, s : String) -> Bool {
  let cu = s.code_units()
  if self.pos + cu.length() > self.src.length() {
    return false
  }
  for i in 0.. String {
  self.text[start:end].to_owned()
}

///|
fn is_space(c : Int32) -> Bool {
  c == 32 || c == 9 || c == 10 || c == 13
}

///|
fn is_name_start(c : Int32) -> Bool {
  (c >= 97 && c <= 122) ||
  (c >= 65 && c <= 90) ||
  c == 95 ||
  c == 58 ||
  c >= 128
}

///|
fn is_name_char(c : Int32) -> Bool {
  is_name_start(c) || (c >= 48 && c <= 57) || c == 45 || c == 46
}

///|
fn Parser::skip_space(self : Parser) -> Unit {
  while is_space(self.peek()) {
    self.pos += 1
  }
}

///|
fn Parser::error(self : Parser, msg : String) -> ParseError {
  ParseError(msg, self.pos)
}

///|
/// Read until the delimiter `until` and return the text before it, leaving
/// the position after the delimiter.
fn Parser::read_until(self : Parser, until : String) -> String raise ParseError {
  let start = self.pos
  while !self.eof() {
    if self.starts_with(until) {
      let s = self.slice(start, self.pos)
      self.pos += until.length()
      return s
    }
    self.pos += 1
  }
  raise self.error("expected '\{until}'")
}

///|
fn Parser::name(self : Parser) -> String raise ParseError {
  let start = self.pos
  guard is_name_start(self.peek()) else { raise self.error("expected a name") }
  while is_name_char(self.peek()) {
    self.pos += 1
  }
  self.slice(start, self.pos)
}

///|
/// Parse an SVG/XML document.
pub fn parse(source : String) -> Document raise ParseError {
  let p : Parser = { text: source, src: source.code_units(), pos: 0, }
  // skip BOM
  if p.peek() == 0xFEFF {
    p.pos += 1
  }
  let children : Array[Node] = []
  p.parse_children(children, None, keep_space=false)
  guard p.eof() else { raise p.error("unexpected content after root element") }
  let roots = children.iter().filter(c => c is Element(_)).count()
  guard roots == 1 else {
    raise ParseError("document must have exactly one root element", 0)
  }
  { children, }
}

///|
/// Parse a sequence of nodes into `out`, stopping at ` Unit raise ParseError {
  while !self.eof() {
    if self.peek() != 60 {
      // text run up to the next markup
      let start = self.pos
      while !self.eof() && self.peek() != 60 {
        self.pos += 1
      }
      let raw = self.slice(start, self.pos)
      if keep_space {
        if parent == Some("style") {
          // In svgo/sax, whitespace-only text tokens adjacent to CDATA or tags in