///|
/// Create an empty builder. Exactly one root node must be added before finish.
pub fn DocumentBuilder::new() -> DocumentBuilder {
  { token: [()], nodes: [], id_index: [], root_index: None, finished: false }
}

///|
fn DocumentBuilder::require_active(
  self : DocumentBuilder,
) -> Unit raise @diagnostic.XPathError {
  if self.finished {
    raise model_error("document builder has already been finished")
  }
}

///|
fn DocumentBuilder::checked_index(
  self : DocumentBuilder,
  node : NodeId,
) -> Int raise @diagnostic.XPathError {
  checked_index(self.token, self.nodes, node)
}

///|
fn DocumentBuilder::append(
  self : DocumentBuilder,
  record : NodeRecord,
) -> NodeId {
  let index = self.nodes.length()
  self.nodes.push(record)
  node_id(self.token, index)
}

///|
fn DocumentBuilder::append_child(
  self : DocumentBuilder,
  parent_index : Int,
  kind : NodeKind,
  name : QName?,
  value : String,
) -> NodeId {
  let child = self.append(new_record(kind, name, value, Some(parent_index)))
  self.nodes[parent_index].children.push(child.index)
  child
}

///|
/// Add the XPath root node.
pub fn DocumentBuilder::add_root(
  self : DocumentBuilder,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  if self.root_index is Some(_) {
    raise model_error("an XPath root node has already been added")
  }
  if !self.nodes.is_empty() {
    raise model_error("the XPath root must be the first arena node")
  }
  let root = self.append(new_record(Root, None, "", None))
  self.root_index = Some(root.index)
  root
}

///|
/// Add an element as a child of `parent`.
pub fn DocumentBuilder::add_element(
  self : DocumentBuilder,
  parent : NodeId,
  name : QName,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  let parent_index = self.checked_index(parent)
  if !is_container(self.nodes[parent_index].kind) {
    raise model_error("an element parent must be the root or another element")
  }
  self.append_child(parent_index, Element, Some(name), "")
}

///|
/// Add an attribute owned by `element`.
///
/// An element cannot contain two attributes with the same expanded name, and
/// the document cannot contain two attributes claiming the same typed-ID
/// value.
pub fn DocumentBuilder::add_attribute(
  self : DocumentBuilder,
  element : NodeId,
  name : QName,
  value : String,
  is_id : Bool,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  let element_index = self.checked_index(element)
  let owner = self.nodes[element_index]
  if owner.kind != Element {
    raise model_error("an attribute owner must be an element")
  }
  for attribute_index in owner.attributes {
    match self.nodes[attribute_index].name {
      Some(existing) =>
        if existing == name {
          raise model_error(
            "an element cannot contain duplicate expanded attribute names",
          )
        }
      None => ()
    }
  }
  if is_id {
    for entry in self.id_index {
      if entry.0 == value {
        raise model_error("typed-ID values must be unique within a document")
      }
    }
  }
  let attribute = self.append(
    new_record(Attribute, Some(name), value, Some(element_index)),
  )
  owner.attributes.push(attribute.index)
  if is_id {
    self.id_index.push((value, element_index))
  }
  attribute
}

///|
/// Materialize one in-scope namespace node for `element`.
///
/// Prefixes are unique per element. Empty URIs, `xmlns`, and a non-standard
/// binding for `xml` are rejected.
pub fn DocumentBuilder::add_namespace(
  self : DocumentBuilder,
  element : NodeId,
  prefix : String,
  uri : String,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  let element_index = self.checked_index(element)
  let owner = self.nodes[element_index]
  if owner.kind != Element {
    raise model_error("a namespace owner must be an element")
  }
  if uri.is_empty() {
    raise model_error("namespace nodes cannot have an empty URI")
  }
  if prefix == XMLNS_PREFIX {
    raise model_error("the reserved xmlns prefix cannot be a namespace node")
  }
  if prefix == XML_PREFIX && uri != XML_NAMESPACE_URI {
    raise model_error("the xml prefix must use its standard namespace URI")
  }
  for namespace_index in owner.namespaces {
    if namespace_prefix_of(self.nodes[namespace_index]) == prefix {
      raise model_error(
        "an element cannot contain duplicate namespace prefixes",
      )
    }
  }
  let name = QName::new(prefix)
  let namespace_node = self.append(
    new_record(Namespace, Some(name), uri, Some(element_index)),
  )
  owner.namespaces.push(namespace_node.index)
  namespace_node
}

///|
/// Add non-empty text. Adjacent text children are coalesced and return the
/// existing text identity.
pub fn DocumentBuilder::add_text(
  self : DocumentBuilder,
  parent : NodeId,
  value : String,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  if value.is_empty() {
    raise model_error("empty text must be skipped by the adapter")
  }
  let parent_index = self.checked_index(parent)
  let owner = self.nodes[parent_index]
  if !is_container(owner.kind) {
    raise model_error("a text parent must be the root or an element")
  }
  match owner.children.last() {
    Some(previous_index) =>
      if self.nodes[previous_index].kind == Text {
        let previous = self.nodes[previous_index]
        previous.value = previous.value + value
        return node_id(self.token, previous_index)
      }
    None => ()
  }
  self.append_child(parent_index, Text, None, value)
}

///|
/// Add a comment node.
pub fn DocumentBuilder::add_comment(
  self : DocumentBuilder,
  parent : NodeId,
  value : String,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  let parent_index = self.checked_index(parent)
  if !is_container(self.nodes[parent_index].kind) {
    raise model_error("a comment parent must be the root or an element")
  }
  self.append_child(parent_index, Comment, None, value)
}

///|
/// Add a processing-instruction node.
pub fn DocumentBuilder::add_processing_instruction(
  self : DocumentBuilder,
  parent : NodeId,
  target : String,
  value : String,
) -> NodeId raise @diagnostic.XPathError {
  self.require_active()
  if target.is_empty() {
    raise model_error("a processing-instruction target cannot be empty")
  }
  let parent_index = self.checked_index(parent)
  if !is_container(self.nodes[parent_index].kind) {
    raise model_error(
      "a processing-instruction parent must be the root or an element",
    )
  }
  self.append_child(
    parent_index,
    ProcessingInstruction,
    Some(QName::new(target)),
    value,
  )
}

///|
fn validate_expanded_name(
  nodes : Array[NodeRecord],
  element_index : Int,
  name : QName,
  attribute : Bool,
) -> Unit raise @diagnostic.XPathError {
  match name.prefix {
    Some(prefix) =>
      if prefix.is_empty() {
        raise model_error("a QName prefix cannot be empty")
      } else {
        match find_namespace_binding(nodes, element_index, prefix) {
          Some(uri) =>
            if name.namespace_uri != Some(uri) {
              raise model_error(
                "a prefixed QName disagrees with its namespace binding",
              )
            }
          None => raise model_error("a prefixed QName has no namespace binding")
        }
      }
    None =>
      if attribute {
        if name.namespace_uri is Some(_) {
          raise model_error(
            "an unprefixed attribute must use the null namespace",
          )
        }
      } else {
        let default_uri = find_namespace_binding(nodes, element_index, "")
        if name.namespace_uri != default_uri {
          raise model_error(
            "an unprefixed element disagrees with the default namespace",
          )
        }
      }
  }
}

///|
fn validate_element_namespaces(
  nodes : Array[NodeRecord],
  element_index : Int,
) -> Unit raise @diagnostic.XPathError {
  match find_namespace_binding(nodes, element_index, XML_PREFIX) {
    Some(uri) =>
      if uri != XML_NAMESPACE_URI {
        raise model_error("the xml namespace binding is not standard")
      }
    None => raise model_error("every element must expose the xml namespace")
  }
  match nodes[element_index].name {
    Some(name) => validate_expanded_name(nodes, element_index, name, false)
    None => raise model_error("an element must have an expanded name")
  }
  for attribute_index in nodes[element_index].attributes {
    match nodes[attribute_index].name {
      Some(name) => validate_expanded_name(nodes, element_index, name, true)
      None => raise model_error("an attribute must have an expanded name")
    }
  }
}

///|
fn push_reversed(stack : Array[Int], values : Array[Int]) -> Unit {
  let mut index = values.length()
  while index > 0 {
    index = index - 1
    stack.push(values[index])
  }
}

///|
fn assign_document_order(
  nodes : Array[NodeRecord],
  root_index : Int,
) -> Unit raise @diagnostic.XPathError {
  let stack = [root_index]
  let mut order = 0
  while stack.pop() is Some(index) {
    let record = nodes[index]
    if record.order >= 0 {
      raise model_error("the document arena contains a cycle")
    }
    record.order = order
    order = order + 1
    if record.kind == Element {
      push_reversed(stack, record.children)
      push_reversed(stack, record.attributes)
      push_reversed(stack, record.namespaces)
    } else if record.kind == Root {
      push_reversed(stack, record.children)
    }
  }
  if order != nodes.length() {
    raise model_error("the document arena contains disconnected nodes")
  }
}

///|
/// Validate all structural invariants and freeze the arena.
pub fn DocumentBuilder::finish(
  self : DocumentBuilder,
) -> Document raise @diagnostic.XPathError {
  self.require_active()
  self.finished = true
  let root_index = match self.root_index {
    Some(index) => index
    None => raise model_error("an XPath root node is required")
  }
  let frozen = self.nodes.map(record => record.deep_copy())
  let root = frozen[root_index]
  let mut document_elements = 0
  for child_index in root.children {
    match frozen[child_index].kind {
      Element => document_elements = document_elements + 1
      ProcessingInstruction | Comment => ()
      Text =>
        raise model_error("root-level text is not part of an XML document")
      _ => raise model_error("the XPath root contains an illegal child kind")
    }
  }
  if document_elements != 1 {
    raise model_error(
      "the XPath root must contain exactly one document element",
    )
  }
  for index in 0..