///|
/// Shared parse state behind every handle.
priv struct Context {
  tree : @internal.Tree
  identity : Int32
}

///|
/// Monotonic source of document identities.
let context_counter : Ref[Int32] = { val: 0, }

///|
/// Create shared context for a freshly parsed tree.
fn Context::new(tree : @internal.Tree) -> Context {
  context_counter.val += 1
  { tree, identity: context_counter.val, }
}

///|
/// A one-based line and column, counted in UTF-16 code units.
///
/// `Document::position` converts a source offset into this. Columns count code
/// units rather than characters, so a character outside the BMP advances the
/// column by two, matching the offsets the rest of this API reports.
#derive(Eq, Debug)
pub(all) struct Position {
  line : Int32
  column : Int32
}

///|
/// The kind of a node, as reported by `Cursor::kind`.
///
/// `Document` is the position `Document::cursor` starts at, and the other
/// variants correspond one to one with the variants of `Node`. Comparing kinds
/// is how a flat walk decides what to do with a cursor without matching on a
/// node value.
#derive(Eq, Debug)
pub(all) enum NodeKind {
  Document
  Element
  Text
  CData
  Comment
  PI
  DocType
}

///|
/// A position in a document, addressed by node id.
///
/// A cursor is a two-field handle over the document, so moving one is a field
/// write rather than a tree search, and a walk builds no intermediate array.
/// Each cursor handed to a visitor is still one small struct, which is the
/// per-node cost a walk pays.
///
/// A cursor can also stand on the document node itself, which `Cursor::kind`
/// reports as `NodeKind::Document` and `Cursor::node` reports as `None`.
///
/// ```mbt check
/// test "navigate with a cursor" {
///   let doc = @xml.parse("")
///   let a = doc.cursor().first_child().unwrap()
///   assert_eq(a.kind(), @xml.NodeKind::Element)
///   let b = a.first_child().unwrap()
///   assert_eq(b.element().unwrap().get_attr("id"), Some("1"))
///   assert_eq(b.next_sibling().unwrap().element().unwrap().name(), "c")
///   assert_eq(b.parent().unwrap().kind(), @xml.NodeKind::Element)
/// }
/// ```
pub struct Cursor {
  priv ctx : Context
  priv id : Int32
}

///|
/// A read-only view of an element's attributes.
///
/// The view borrows the document's cached `[name, value, ...]` pairs: creating
/// it copies nothing, and it stays valid for as long as the document does.
/// Names keep their authored case and prefix; values are entity-decoded.
///
/// Lookups are linear in the number of attributes, which is the right trade for
/// the usual handful of them. `to_map` builds a real map when a long list is
/// queried repeatedly.
///
/// ```mbt check
/// test "read attributes through the view" {
///   let doc = @xml.parse("")
///   let attrs = doc.root().unwrap().attributes()
///   assert_eq(attrs.length(), 2)
///   assert_eq(attrs.get("b"), Some("x & y"))
///   assert_true(attrs.has("a"))
///   let seen : Array[String] = []
///   attrs.each(fn(name, value) { seen.push("\{name}=\{value}") })
///   assert_eq(seen, ["a=1", "b=x & y"])
/// }
/// ```
pub struct Attributes {
  priv pairs : Array[String]
}

///|
/// The parent of a node: the document itself, or an element.
///
/// `Cursor::parent` reports a position rather than a `Parent`, so this is the
/// typed form for callers that want to match on which of the two it is.
#derive(Eq, Debug)
pub(all) enum Parent {
  Document(Document)
  Element(Element)
}

///|
/// A parsed XML document.
///
/// A document owns the source string and the compact tree built from it, and
/// every `Element`, `Text`, and `Cursor` obtained from it is a handle into that
/// shared state. Handles stay valid for as long as the document does, and two
/// handles compare equal exactly when they point at the same node of the same
/// document.
///
/// ```mbt check
/// test "a document is the entry point" {
///   let doc = @xml.parse("")
///   assert_eq(doc.source(), "")
///   assert_eq(doc.stringify(), "")
///   assert_true(doc.is_well_formed())
/// }
/// ```
pub struct Document {
  priv ctx : Context
}

///|
/// An element node.
///
/// Reading a name, an attribute, or the text allocates only what was asked for
/// and caches it on the document, so asking twice decodes once.
pub struct Element {
  priv ctx : Context
  priv id : Int32
}

///|
/// A text node.
///
/// The source is kept as written: `Text::value` decodes entity and character
/// references, `Text::raw` does not. A run of text between two tags is one
/// node, even when it contains references.
pub struct Text {
  priv ctx : Context
  priv id : Int32
}

///|
/// A CDATA section.
///
/// Its content is never decoded: `` yields the literal
/// `a & b`, seven characters that look like a reference and are not one.
pub struct CData {
  priv ctx : Context
  priv id : Int32
}

///|
/// A comment, from ``.
pub struct Comment {
  priv ctx : Context
  priv id : Int32
}

///|
/// A processing instruction, including the XML declaration.
///
/// `` is a `PI` whose target is `xml` and whose data is
/// `version="1.0"`; the declaration is not special-cased beyond that.
pub struct PI {
  priv ctx : Context
  priv id : Int32
}

///|
/// A `` declaration.
///
/// The declaration is recorded as written. Its internal subset is scanned for
/// general entity declarations, and nothing else in it is interpreted.
pub struct DocType {
  priv ctx : Context
  priv id : Int32
}

///|
/// Any node in the tree, as returned by `Document::children` and
/// `Element::children`.
///
/// `Node` is an enum of handles, so matching on it is how a caller distinguishes
/// the kinds without asking `Cursor::kind` first, and without losing the typed
/// accessors each variant carries.
#derive(Eq, Debug)
pub(all) enum Node {
  Element(Element)
  Text(Text)
  CData(CData)
  Comment(Comment)
  PI(PI)
  DocType(DocType)
}

///|
/// Parse an XML document.
///
/// The parser never fails: markup it cannot make sense of is recorded in
/// `Document::error` and parsing continues from the next `<`. Every node keeps
/// its source offsets, so the document round-trips by slicing the original
/// string.
///
/// Parsing is one pass over `source`, and the tree is allocated in proportion to
/// the number of nodes rather than to the number of bytes. Nothing is decoded
/// until it is read.
///
/// ```mbt check
/// test "parse recovers instead of throwing" {
///   let doc = @xml.parse("")
///   assert_false(doc.is_well_formed())
///   assert_eq(doc.error(), Some(6))
///   assert_eq(doc.position(6), { line: 1, column: 7, })
/// }
/// ```
pub fn parse(source : String) -> Document {
  { ctx: Context::new(@internal.build(source)), }
}

///|
pub impl Eq for Document with fn equal(self, other) {
  self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for Element with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for Text with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for CData with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for Comment with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for PI with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Eq for DocType with fn equal(self, other) {
  self.id == other.id && self.ctx.identity == other.ctx.identity
}

///|
pub impl Debug for Text with fn to_repr(self) {
  Repr::Repr("Text(\{self.value()})")
}

///|
pub impl Debug for CData with fn to_repr(self) {
  Repr::Repr("CData(\{self.value()})")
}

///|
pub impl Debug for Comment with fn to_repr(self) {
  Repr::Repr("Comment(\{self.value()})")
}

///|
pub impl Debug for PI with fn to_repr(self) {
  Repr::Repr("PI(\{self.target()})")
}

///|
pub impl Debug for DocType with fn to_repr(self) {
  Repr::Repr("DocType(offsets=\{self.start()}..\{self.end()})")
}

///|
fn wrap(ctx : Context, id : Int32) -> Node {
  match ctx.tree.kind[id] {
    @internal.Kind::Element => Node::Element({ ctx, id, })
    @internal.Kind::Text => Node::Text({ ctx, id, })
    @internal.Kind::CData => Node::CData({ ctx, id, })
    @internal.Kind::Comment => Node::Comment({ ctx, id, })
    @internal.Kind::PI => Node::PI({ ctx, id, })
    @internal.Kind::DocType => Node::DocType({ ctx, id, })
    @internal.Kind::Document => abort("document cannot be a child node")
  }
}

///|
fn walk_nodes(ctx : Context, root : Int32, visit : (Cursor) -> Unit) -> Unit {
  let stop = ctx.tree.stop[root]
  let mut id = root + 1
  while id < stop {
    visit({ ctx, id, })
    id += 1
  }
}

///|
fn children(ctx : Context, id : Int32) -> Array[Node] {
  let output : Array[Node] = []
  let tree = ctx.tree
  let stop = tree.stop[id]
  let mut current = id + 1
  while current < stop {
    output.push(wrap(ctx, current))
    current = tree.stop[current]
  }
  output
}

///|
/// The offset of the first `:` in a name, or -1.
fn colon_at(name : String) -> Int32 {
  let mut i = 0
  while i < name.length() {
    if name.unsafe_get(i).to_int() == 58 {
      return i
    }
    i += 1
  }
  -1
}

///|
/// Whether a name matches `query` as written or by its local part.
fn name_matches(name : String, query : String) -> Bool {
  if name == query {
    return true
  }
  let at = colon_at(name)
  if at == -1 {
    return false
  }
  @internal.slice(name, at + 1, name.length()) == query
}

///|
/// The source text the document was parsed from, exactly as given.
///
/// The string is not copied: it is the value that was passed to `parse`.
pub fn Document::source(self : Document) -> String {
  self.ctx.tree.source
}

///|
/// The offset where the document starts, always 0.
///
/// It exists so that a document and an element can be handled by the same code
/// through `start` and `end`.
pub fn Document::start(_self : Document) -> Int32 {
  0
}

///|
/// The offset just past the last code unit of the source.
///
/// This is `source().length()`, not the end of the root element: trailing
/// comments and whitespace after the root are part of the document.
pub fn Document::end(self : Document) -> Int32 {
  self.ctx.tree.source.length()
}

///|
/// The document's root element, or `None` when it has none.
///
/// The first element child of the document node is the root; the declaration,
/// comments, and processing instructions that precede it are skipped, as are
/// any that follow it.
///
/// ```mbt check
/// test "root skips the prolog" {
///   let doc = @xml.parse("")
///   assert_eq(doc.root().unwrap().name(), "r")
///   assert_eq(doc.root().unwrap().children().length(), 0)
/// }
/// ```
pub fn Document::root(self : Document) -> Element? {
  let tree = self.ctx.tree
  let mut current = 1
  while current < tree.size {
    if tree.kind[current] == @internal.Kind::Element {
      return Some({ ctx: self.ctx, id: current, })
    }
    current = tree.stop[current]
  }
  None
}

///|
/// The document's direct children, excluding the document node itself.
///
/// This is where the prolog and any top-level comments or processing
/// instructions appear, in source order. The array is built on each call and
/// holds handles, so it costs one slot per child and nothing per node.
pub fn Document::children(self : Document) -> Array[Node] {
  children(self.ctx, 0)
}

///|
/// A cursor at the document node.
///
/// `Cursor::kind` reports `NodeKind::Document` here, `Cursor::node` returns
/// `None`, and `Cursor::first_child` moves to the first item of the prolog.
pub fn Document::cursor(self : Document) -> Cursor {
  { ctx: self.ctx, id: 0, }
}

///|
/// Visit every node in the document in document order, the document node
/// excluded.
///
/// The walk is a flat scan over node ids: it does not recurse, so depth is
/// bounded by the tree rather than by the stack, and it builds no intermediate
/// array.
///
/// ```mbt check
/// test "walk counts nodes by kind" {
///   let doc = @xml.parse("t")
///   let kinds : Array[@xml.NodeKind] = []
///   doc.walk(fn(cursor) { kinds.push(cursor.kind()) })
///   assert_eq(kinds.length(), 4)
///   assert_eq(kinds[0], @xml.NodeKind::Element)
///   assert_eq(kinds[1], @xml.NodeKind::Text)
///   assert_eq(kinds[2], @xml.NodeKind::Comment)
///   assert_eq(kinds[3], @xml.NodeKind::Element)
/// }
/// ```
pub fn Document::walk(self : Document, visit : (Cursor) -> Unit) -> Unit {
  walk_nodes(self.ctx, 0, visit)
}

///|
/// The first element whose name matches `query`, in document order.
///
/// `query` matches the qualified name as written or the local part, so both
/// `find("p:item")` and `find("item")` find ``. Matching is
/// case-sensitive and ignores namespaces: two prefixes bound to the same URI
/// are still different names.
///
/// The scan is linear in the number of nodes. For repeated queries against a
/// large document, collect `all` once and index the result.
///
/// ```mbt check
/// test "find matches the local part" {
///   let doc = @xml.parse(
///     "12",
///   )
///   assert_eq(doc.find("item").unwrap().text(), "1")
///   assert_eq(doc.find("p:item").unwrap().text(), "1")
///   assert_eq(doc.all("item").length(), 2)
/// }
/// ```
pub fn Document::find(self : Document, query : String) -> Element? {
  let tree = self.ctx.tree
  let mut current = 1
  while current < tree.size {
    if tree.kind[current] == @internal.Kind::Element &&
      name_matches(tree.names.get(tree.name[current]), query) {
      return Some({ ctx: self.ctx, id: current, })
    }
    current += 1
  }
  None
}

///|
/// Every element whose name matches `query`, in document order.
///
/// The matching rules are those of `Document::find`; the result holds handles,
/// so building it is cheap, but it is a snapshot and is not updated by later
/// calls.
pub fn Document::all(self : Document, query : String) -> Array[Element] {
  let output : Array[Element] = []
  let tree = self.ctx.tree
  let mut current = 1
  while current < tree.size {
    if tree.kind[current] == @internal.Kind::Element &&
      name_matches(tree.names.get(tree.name[current]), query) {
      output.push({ ctx: self.ctx, id: current, })
    }
    current += 1
  }
  output
}

///|
/// The offset of the first structural problem, or `None` when the document is
/// well formed.
///
/// The parser recovers and keeps going, so this reports where recovery first
/// happened rather than where parsing stopped. The offset is a source offset,
/// which `position` turns into a line and column.
///
/// ```mbt check
/// test "an error carries its offset" {
///   let doc = @xml.parse("\n  \n")
///   let at = doc.error().unwrap()
///   assert_eq(at, 10)
///   assert_eq(doc.position(at), { line: 3, column: 1, })
/// }
/// ```
pub fn Document::error(self : Document) -> Int32? {
  self.ctx.tree.error
}

///|
/// Whether the document parsed without structural problems.
///
/// Equivalent to `error() is None`, and cheaper to read at the call site than
/// comparing the option.
pub fn Document::is_well_formed(self : Document) -> Bool {
  self.ctx.tree.error is None
}

///|
/// The line and column of a source offset.
///
/// Both are one-based and counted in UTF-16 code units, so offset 0 is line 1,
/// column 1. Offsets past the end are clamped to the end of the source, and a
/// negative offset is treated as 0.
///
/// The scan is linear in `offset`, so converting many offsets one at a time is
/// quadratic in the length of the document; converting them in ascending order
/// in one pass is not.
///
/// ```mbt check
/// test "position maps offsets to lines" {
///   let doc = @xml.parse("\n\n")
///   assert_eq(doc.position(0), { line: 1, column: 1, })
///   assert_eq(doc.position(4), { line: 2, column: 1, })
///   assert_eq(doc.position(9), { line: 3, column: 1, })
/// }
/// ```
pub fn Document::position(self : Document, offset : Int32) -> Position {
  let source = self.ctx.tree.source
  let limit = if offset < source.length() { offset } else { source.length() }
  let mut line = 1
  let mut column = 1
  let mut i = 0
  while i < limit {
    if source.unsafe_get(i).to_int() == 10 {
      line += 1
      column = 1
    } else {
      column += 1
    }
    i += 1
  }
  { line, column, }
}

///|
/// The document's source text, unchanged.
///
/// Nothing is re-serialized: the tree stores offsets into the original string,
/// so a round trip returns exactly what was parsed, including comments,
/// whitespace, and the author's choice of quoting.
pub fn Document::stringify(self : Document) -> String {
  self.ctx.tree.source
}

///|
pub impl Debug for Document with fn to_repr(self) {
  Repr::Repr("Document(offsets=0..\{self.end()})")
}

///|
/// The kind of node this cursor stands on.
///
/// `NodeKind::Document` only appears for the cursor returned by
/// `Document::cursor`; every cursor produced by walking stands on a node.
pub fn Cursor::kind(self : Cursor) -> NodeKind {
  match self.ctx.tree.kind[self.id] {
    @internal.Kind::Document => NodeKind::Document
    @internal.Kind::Element => NodeKind::Element
    @internal.Kind::Text => NodeKind::Text
    @internal.Kind::CData => NodeKind::CData
    @internal.Kind::Comment => NodeKind::Comment
    @internal.Kind::PI => NodeKind::PI
    @internal.Kind::DocType => NodeKind::DocType
  }
}

///|
/// The element at this position, or `None` when the node is not an element.
///
/// This is the bridge from a flat walk to the element API: `walk` hands out
/// cursors, and this turns the ones that are elements into `Element`.
///
/// ```mbt check
/// test "collect elements during a walk" {
///   let doc = @xml.parse("")
///   let names : Array[String] = []
///   doc.walk(fn(cursor) {
///     if cursor.element() is Some(element) {
///       names.push(element.name())
///     }
///   })
///   assert_eq(names, ["r", "a", "b"])
/// }
/// ```
pub fn Cursor::element(self : Cursor) -> Element? {
  if self.ctx.tree.kind[self.id] == @internal.Kind::Element {
    Some({ ctx: self.ctx, id: self.id, })
  } else {
    None
  }
}

///|
/// The node at this position, or `None` for the document node.
///
/// Unlike `element`, this wraps every kind, which is what a caller needs when
/// the kind is not known in advance.
pub fn Cursor::node(self : Cursor) -> Node? {
  if self.ctx.tree.kind[self.id] == @internal.Kind::Document {
    None
  } else {
    Some(wrap(self.ctx, self.id))
  }
}

///|
/// The first child of this position, or `None` when it has none.
///
/// The first child is the node one id past this one, because ids are assigned
/// in document order. An empty element and a self-closing one both report
/// `None`.
pub fn Cursor::first_child(self : Cursor) -> Cursor? {
  let next = self.id + 1
  if next < self.ctx.tree.stop[self.id] {
    Some({ ctx: self.ctx, id: next, })
  } else {
    None
  }
}

///|
/// The next sibling of this position, or `None` at the end of the parent.
///
/// A node with children owns the whole id range up to its subtree end, so the
/// next sibling starts there. Skipping a sibling therefore costs the same
/// whether it is empty or has a thousand descendants.
pub fn Cursor::next_sibling(self : Cursor) -> Cursor? {
  let tree = self.ctx.tree
  let parent = tree.parent[self.id]
  if parent < 0 {
    return None
  }
  let next = tree.stop[self.id]
  if next < tree.stop[parent] {
    Some({ ctx: self.ctx, id: next, })
  } else {
    None
  }
}

///|
/// The parent position, or `None` for the document node.
///
/// Walking up from the root element yields a cursor on the document, whose own
/// `parent` is `None`. Nothing else reports `None`, because every node in the
/// tree has a parent.
pub fn Cursor::parent(self : Cursor) -> Cursor? {
  let parent = self.ctx.tree.parent[self.id]
  if parent < 0 {
    None
  } else {
    Some({ ctx: self.ctx, id: parent, })
  }
}

///|
/// The element's qualified name, with its namespace prefix if it has one.
///
/// The name is interned at parse time, so this is a table lookup rather than a
/// copy of the source.
pub fn Element::name(self : Element) -> String {
  self.ctx.tree.names.get(self.ctx.tree.name[self.id])
}

///|
/// The namespace prefix, or `""` when the name is unprefixed.
///
/// `p:item` has prefix `p`, and `item` has prefix `""`. This is the prefix the
/// name was written with, not what the declaration binds it to; resolving it is
/// `namespace_uri`'s job.
pub fn Element::prefix(self : Element) -> String {
  let name = self.name()
  let at = colon_at(name)
  if at == -1 {
    ""
  } else {
    @internal.slice(name, 0, at)
  }
}

///|
/// The local part of the name, without any prefix.
///
/// Both `p:item` and `item` have local name `item`. Only the first colon
/// separates the prefix, so a name with more than one keeps the rest.
pub fn Element::local_name(self : Element) -> String {
  let name = self.name()
  let at = colon_at(name)
  if at == -1 {
    name
  } else {
    @internal.slice(name, at + 1, name.length())
  }
}

///|
/// The namespace URI the element's prefix is bound to, or `None`.
///
/// An unprefixed element resolves through the default namespace; when no
/// declaration is in scope it has no namespace. `xmlns=""` unbinds the default
/// namespace and yields `None`. The `xml` prefix is bound to
/// `http://www.w3.org/XML/1998/namespace` without a declaration, as the spec
/// requires.
///
/// Resolution is lazy: the bindings in scope are collected and cached the first
/// time an element is asked, so a parse that never asks costs nothing.
///
/// ```mbt check
/// test "resolve namespaces" {
///   let doc = @xml.parse("")
///   let p = doc.find("i").unwrap()
///   assert_eq(p.prefix(), "p")
///   assert_eq(p.namespace_uri(), Some("urn:p"))
///   assert_eq(doc.find("j").unwrap().namespace_uri(), Some("urn:d"))
/// }
/// ```
pub fn Element::namespace_uri(self : Element) -> String? {
  @internal.namespace_uri(self.ctx.tree, self.id, self.prefix())
}

///|
/// The namespace URI of one of the element's attributes, or `None`.
///
/// Unprefixed attributes are in no namespace, as XML requires: a default
/// declaration does not apply to them, so `attr_namespace_uri("id")` is `None`
/// even inside a document whose default namespace is set.
///
/// ```mbt check
/// test "attributes need an explicit prefix" {
///   let doc = @xml.parse(
///     "",
///   )
///   let r = doc.root().unwrap()
///   assert_eq(r.attr_namespace_uri("q:id"), Some("urn:q"))
///   assert_eq(r.attr_namespace_uri("id"), None)
/// }
/// ```
pub fn Element::attr_namespace_uri(self : Element, name : String) -> String? {
  let at = colon_at(name)
  if at == -1 {
    None
  } else {
    @internal.namespace_uri(
      self.ctx.tree,
      self.id,
      @internal.slice(name, 0, at),
    )
  }
}

///|
/// The element's attributes as a read-only view.
///
/// The first call scans the start tag and caches the pairs on the document;
/// later calls return the same view. `Attributes::to_map` is the one operation
/// that copies.
pub fn Element::attributes(self : Element) -> Attributes {
  { pairs: @internal.pairs(self.ctx.tree, self.id), }
}

///|
/// The value of one attribute, matched exactly, or `None`.
///
/// The name is compared as written: case-sensitive, prefix included, and not
/// resolved through namespaces, so `get_attr("id")` does not find `q:id`. The
/// value is entity-decoded.
pub fn Element::get_attr(self : Element, name : String) -> String? {
  @internal.attribute(self.ctx.tree, self.id, name)
}

///|
/// Whether the attribute is present, matched exactly.
///
/// The same matching rules as `get_attr`, for callers that only care about
/// presence.
pub fn Element::has_attr(self : Element, name : String) -> Bool {
  self.get_attr(name) is Some(_)
}

///|
/// The number of attributes on the element.
pub fn Attributes::length(self : Attributes) -> Int32 {
  self.pairs.length() / 2
}

///|
/// Whether the element has no attributes at all.
pub fn Attributes::is_empty(self : Attributes) -> Bool {
  self.pairs.is_empty()
}

///|
/// The decoded value of an attribute, or `None` when absent.
///
/// Lookup is linear and compares names exactly, the same rules `Element::get_attr`
/// applies; the difference is that this one does not go back to the element.
pub fn Attributes::get(self : Attributes, name : String) -> String? {
  let at = @internal.find_pair(self.pairs, name)
  if at == -1 {
    None
  } else {
    Some(self.pairs[at + 1])
  }
}

///|
/// Whether the attribute is present, matched exactly.
pub fn Attributes::has(self : Attributes, name : String) -> Bool {
  @internal.find_pair(self.pairs, name) != -1
}

///|
/// Call `visit` with every attribute name and value, in source order.
///
/// Nothing is allocated for the iteration itself: the callback receives the
/// cached strings, and source order means the result is stable across runs.
pub fn Attributes::each(
  self : Attributes,
  visit : (String, String) -> Unit,
) -> Unit {
  let mut i = 0
  while i < self.pairs.length() {
    visit(self.pairs[i], self.pairs[i + 1])
    i += 2
  }
}

///|
/// An independent, mutable copy of the attributes as a map.
///
/// The view itself cannot be modified; this is how a caller gets something to
/// edit. A duplicated name keeps the value that appears last, which is also
/// what the parser records in the view.
pub fn Attributes::to_map(self : Attributes) -> Map[String, String] {
  let output : Map[String, String] = Map([])
  let mut i = 0
  while i < self.pairs.length() {
    output[self.pairs[i]] = self.pairs[i + 1]
    i += 2
  }
  output
}

///|
pub impl Eq for Attributes with fn equal(self, other) {
  self.pairs == other.pairs
}

///|
pub impl Debug for Attributes with fn to_repr(self) {
  Repr::Repr("Attributes(\{self.length()})")
}

///|
/// The element's direct children: text, elements, comments, CDATA, and
/// processing instructions, in source order.
///
/// The array is built on each call and holds handles, so it costs one slot per
/// child. `elements` is the filtered version, and `walk` visits the whole
/// subtree without building either.
pub fn Element::children(self : Element) -> Array[Node] {
  children(self.ctx, self.id)
}

///|
/// The element's direct child elements, skipping text and the rest.
///
/// Whitespace-only text between elements is still a text node, so this is
/// usually what a caller wants instead of filtering `children` by hand.
pub fn Element::elements(self : Element) -> Array[Element] {
  let output : Array[Element] = []
  let tree = self.ctx.tree
  let stop = tree.stop[self.id]
  let mut current = self.id + 1
  while current < stop {
    if tree.kind[current] == @internal.Kind::Element {
      output.push({ ctx: self.ctx, id: current, })
    }
    current = tree.stop[current]
  }
  output
}

///|
/// A cursor at this element.
///
/// Useful for mixing the element API with cursor navigation, for example to
/// keep walking from a node that was found by name.
pub fn Element::cursor(self : Element) -> Cursor {
  { ctx: self.ctx, id: self.id, }
}

///|
/// Visit every descendant of this element, the element itself excluded.
///
/// The walk is a flat scan over ids: it does not recurse, so 2000 levels of
/// nesting are walked in a loop rather than on the stack.
pub fn Element::walk(self : Element, visit : (Cursor) -> Unit) -> Unit {
  walk_nodes(self.ctx, self.id, visit)
}

///|
/// The first descendant element whose name matches `query`.
///
/// Descendants only: the element itself is never returned. Matching follows
/// `Document::find`, qualified name or local part, case-sensitive.
pub fn Element::find(self : Element, query : String) -> Element? {
  let tree = self.ctx.tree
  let mut current = self.id + 1
  let stop = tree.stop[self.id]
  while current < stop {
    if tree.kind[current] == @internal.Kind::Element &&
      name_matches(tree.names.get(tree.name[current]), query) {
      return Some({ ctx: self.ctx, id: current, })
    }
    current += 1
  }
  None
}

///|
/// Every descendant element whose name matches `query`, in document order.
///
/// The element itself is not included, even when it matches.
pub fn Element::all(self : Element, query : String) -> Array[Element] {
  let output : Array[Element] = []
  let tree = self.ctx.tree
  let stop = tree.stop[self.id]
  let mut current = self.id + 1
  while current < stop {
    if tree.kind[current] == @internal.Kind::Element &&
      name_matches(tree.names.get(tree.name[current]), query) {
      output.push({ ctx: self.ctx, id: current, })
    }
    current += 1
  }
  output
}

///|
/// The decoded text of all descendant text and CDATA nodes, concatenated.
///
/// Element boundaries contribute nothing, so `xyz` has the text
/// `xyz`. CDATA content is appended verbatim, which is what the section means
/// and why a reference written inside one is not expanded. The result is built
/// on first read and cached on the document.
///
/// ```mbt check
/// test "text concatenates across descendants" {
///   let doc = @xml.parse("xyz")
///   assert_eq(doc.root().unwrap().text(), "xyz&")
/// }
/// ```
pub fn Element::text(self : Element) -> String {
  @internal.text(self.ctx.tree, self.id)
}

///|
/// The raw source between this element's open and close tags.
///
/// Nothing is decoded or re-serialized: this is a slice of the source, so
/// `&` stays `&` and `` stays ``. `text` is the decoded
/// alternative.
pub fn Element::inner(self : Element) -> String {
  @internal.slice(
    self.ctx.tree.source,
    self.ctx.tree.from[self.id],
    self.ctx.tree.to[self.id],
  )
}

///|
/// Whether the element was written as ``.
///
/// This is a fact about the source, not about the content: `` and ``
/// both have no children, and only the second reports `true`.
pub fn Element::is_empty_element(self : Element) -> Bool {
  let tree = self.ctx.tree
  tree.end[self.id] - 2 >= tree.start[self.id] &&
  tree.source.unsafe_get(tree.end[self.id] - 2).to_int() == 47
}

///|
/// The offset of the `<` that opens the element.
pub fn Element::start(self : Element) -> Int32 {
  self.ctx.tree.start[self.id]
}

///|
/// The offset just past the `>` that closes the element.
///
/// For `` this is the end of the tag itself, so `end - start` is the length
/// of the markup and `stringify` reproduces it exactly.
pub fn Element::end(self : Element) -> Int32 {
  self.ctx.tree.end[self.id]
}

///|
/// The element's source text, from `<` to the end of its close tag.
///
/// Because the tree stores offsets, this is a slice of the original source and
/// reproduces the authored markup exactly, nested nodes included.
pub fn Element::stringify(self : Element) -> String {
  @internal.slice(self.ctx.tree.source, self.start(), self.end())
}

///|
pub impl Debug for Element with fn to_repr(self) {
  Repr::Repr("Element(\{self.name()}, offsets=\{self.start()}..\{self.end()})")
}

///|
/// The decoded text of a text node.
///
/// Entity and character references are replaced, and the result is cached on the
/// document, so reading the same node twice decodes once. `raw` returns the
/// source instead.
///
/// ```mbt check
/// test "text decodes and raw does not" {
///   let doc = @xml.parse("x & A")
///   let text = match doc.root().unwrap().children()[0] {
///     @xml.Node::Text(text) => text
///     _ => abort("expected a text node")
///   }
///   assert_eq(text.value(), "x & A")
///   assert_eq(text.raw(), "x & A")
/// }
/// ```
pub fn Text::value(self : Text) -> String {
  @internal.value(self.ctx.tree, self.id)
}

///|
/// The raw content of a text node, before entity decoding.
///
/// A slice of the source, so it is what the author wrote, references and all.
pub fn Text::raw(self : Text) -> String {
  @internal.slice(
    self.ctx.tree.source,
    self.ctx.tree.from[self.id],
    self.ctx.tree.to[self.id],
  )
}

///|
/// The offset of the text node's first code unit.
///
/// Unlike the marked-up nodes, a text node's range covers its content only;
/// there are no delimiters to include.
pub fn Text::start(self : Text) -> Int32 {
  self.ctx.tree.from[self.id]
}

///|
/// The offset just past the text node's last code unit.
pub fn Text::end(self : Text) -> Int32 {
  self.ctx.tree.to[self.id]
}

///|
/// The content of a CDATA section, without the ``.
///
/// CDATA is literal by definition, so this is a slice of the source: `&`
/// inside a section stays five characters.
pub fn CData::value(self : CData) -> String {
  @internal.value(self.ctx.tree, self.id)
}

///|
/// The offset of the `<` in ` Int32 {
  self.ctx.tree.start[self.id]
}

///|
/// The offset just past the `>` in `]]>`.
pub fn CData::end(self : CData) -> Int32 {
  self.ctx.tree.end[self.id]
}

///|
/// The content of a comment, without the `` delimiters.
pub fn Comment::value(self : Comment) -> String {
  @internal.value(self.ctx.tree, self.id)
}

///|
/// The offset of the `<` in ``.
pub fn Comment::end(self : Comment) -> Int32 {
  self.ctx.tree.end[self.id]
}

///|
/// The target of a processing instruction, e.g. `xml` for the declaration.
///
/// The target is the name immediately after ` String {
  @internal.target(self.ctx.tree, self.id)
}

///|
/// The data of a processing instruction, without the leading whitespace.
///
/// For `` the data is `version="1.0"`; for `` it is
/// the empty string.
pub fn PI::data(self : PI) -> String {
  @internal.data(self.ctx.tree, self.id)
}

///|
/// The offset of the `<` in `` included.
pub fn PI::start(self : PI) -> Int32 {
  self.ctx.tree.start[self.id]
}

///|
/// The offset just past the `>` in `?>`.
pub fn PI::end(self : PI) -> Int32 {
  self.ctx.tree.end[self.id]
}

///|
/// The declaration's text between ``, without the leading
/// whitespace.
///
/// For `` this is `html`. The internal subset, if any, is part
/// of the same string.
pub fn DocType::value(self : DocType) -> String {
  let raw = @internal.value(self.ctx.tree, self.id)
  let mut start = 0
  while start < raw.length() &&
        @internal.is_space(raw.unsafe_get(start).to_int()) {
    start += 1
  }
  if start == 0 {
    raw
  } else {
    @internal.slice(raw, start, raw.length())
  }
}

///|
/// The offset of the `<` in ` Int32 {
  self.ctx.tree.start[self.id]
}

///|
/// The offset just past the `>` that ends the declaration.
pub fn DocType::end(self : DocType) -> Int32 {
  self.ctx.tree.end[self.id]
}

///|
/// The offset where the node starts, whatever its kind.
///
/// For a text node this is its first character; for the marked-up kinds it is
/// the `<` of the construct.
pub fn Node::start(self : Node) -> Int32 {
  match self {
    Element(node) => node.start()
    Text(node) => node.start()
    CData(node) => node.start()
    Comment(node) => node.start()
    PI(node) => node.start()
    DocType(node) => node.start()
  }
}

///|
/// The offset where the node ends, whatever its kind.
pub fn Node::end(self : Node) -> Int32 {
  match self {
    Element(node) => node.end()
    Text(node) => node.end()
    CData(node) => node.end()
    Comment(node) => node.end()
    PI(node) => node.end()
    DocType(node) => node.end()
  }
}

///|
/// The node's source text, whatever its kind.
///
/// A slice of the original source, so a node round-trips exactly and nested
/// nodes come along with it.
pub fn Node::stringify(self : Node) -> String {
  let (ctx, start, end) = match self {
    Element(node) => (node.ctx, node.start(), node.end())
    Text(node) => (node.ctx, node.start(), node.end())
    CData(node) => (node.ctx, node.start(), node.end())
    Comment(node) => (node.ctx, node.start(), node.end())
    PI(node) => (node.ctx, node.start(), node.end())
    DocType(node) => (node.ctx, node.start(), node.end())
  }
  @internal.slice(ctx.tree.source, start, end)
}