///|
/// Per-evaluation accounting. The AST is bounded at compile time; this state
/// bounds dynamic traversal, predicates and function work independently.
priv struct EvaluationState {
  limits : @context.EvaluationLimits
  mut steps : Int
}

///|
fn EvaluationState::charge(
  self : EvaluationState,
) -> Unit raise @diagnostic.XPathError {
  self.steps = self.steps + 1
  if self.steps > self.limits.max_steps() {
    raise LimitExceeded(phase=Evaluate, limit="max_steps")
  }
}

///|
fn[T] raise_evaluate(
  span : @diagnostic.SourceSpan,
  message : String,
) -> T raise @diagnostic.XPathError {
  raise Evaluate(span=Some(span), message~)
}

///|
fn normalize_document_order(
  document : @model.Document,
  nodes : Array[@model.NodeId],
) -> @value.NodeSet raise @diagnostic.XPathError {
  @value.NodeSet::new(document, nodes)
}

///|
fn limited_node_set(
  document : @model.Document,
  nodes : Array[@model.NodeId],
  state : EvaluationState,
) -> @value.NodeSet raise @diagnostic.XPathError {
  if nodes.length() > state.limits.max_nodeset_size() {
    raise LimitExceeded(phase=Evaluate, limit="max_nodeset_size")
  }
  let normalized = normalize_document_order(document, nodes)
  if normalized.length() > state.limits.max_nodeset_size() {
    raise LimitExceeded(phase=Evaluate, limit="max_nodeset_size")
  }
  normalized
}

///|
fn require_nodes(
  value : @value.XPathValue,
  span : @diagnostic.SourceSpan,
  purpose : String,
) -> @value.NodeSet raise @diagnostic.XPathError {
  match value {
    Nodes(nodes) => nodes
    _ => raise_evaluate(span, purpose + " requires a node-set")
  }
}

///|
fn number_literal(
  text : String,
  span : @diagnostic.SourceSpan,
) -> Double raise @diagnostic.XPathError {
  @string.parse_double(text) catch {
    _ => raise_evaluate(span, "invalid XPath number literal")
  }
}

///|
fn context_as_nodes(
  context : @context.DynamicContext,
  state : EvaluationState,
) -> @value.NodeSet raise @diagnostic.XPathError {
  limited_node_set(context.document(), [context.context_node()], state)
}

///|
fn document_nodes(
  document : @model.Document,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  let result : Array[@model.NodeId] = []
  let stack = [document.root()]
  while stack.pop() is Some(node) {
    state.charge()
    result.push(node)
    if document.kind(node) == Element {
      for namespace_node in document.namespaces(node) {
        state.charge()
        result.push(namespace_node)
      }
      for attribute_node in document.attributes(node) {
        state.charge()
        result.push(attribute_node)
      }
    }
    let children = document.children(node)
    let mut index = children.length()
    while index > 0 {
      index = index - 1
      stack.push(children[index])
    }
  }
  result
}

///|
fn is_ancestor(
  document : @model.Document,
  candidate : @model.NodeId,
  node : @model.NodeId,
  state : EvaluationState,
) -> Bool raise @diagnostic.XPathError {
  let mut current = document.parent(node)
  while current is Some(parent) {
    state.charge()
    if parent == candidate {
      return true
    }
    current = document.parent(parent)
  }
  false
}

///|
fn collect_descendants(
  document : @model.Document,
  node : @model.NodeId,
  include_self : Bool,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  let result : Array[@model.NodeId] = []
  let stack : Array[@model.NodeId] = []
  if include_self {
    stack.push(node)
  } else {
    let children = document.children(node)
    let mut index = children.length()
    while index > 0 {
      index = index - 1
      stack.push(children[index])
    }
  }
  while stack.pop() is Some(current) {
    state.charge()
    result.push(current)
    let children = document.children(current)
    let mut index = children.length()
    while index > 0 {
      index = index - 1
      stack.push(children[index])
    }
  }
  result
}

///|
fn sibling_axis_nodes(
  document : @model.Document,
  node : @model.NodeId,
  following : Bool,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  match document.parent(node) {
    None => []
    Some(parent) => {
      let siblings = document.children(parent)
      let mut current_index = -1
      for index, sibling in siblings {
        state.charge()
        if sibling == node {
          current_index = index
          break
        }
      }
      if current_index < 0 {
        []
      } else {
        let result : Array[@model.NodeId] = []
        if following {
          for index in (current_index + 1).. 0 {
            index = index - 1
            state.charge()
            result.push(siblings[index])
          }
        }
        result
      }
    }
  }
}

///|
fn following_or_preceding_nodes(
  document : @model.Document,
  node : @model.NodeId,
  following : Bool,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  let all_nodes = document_nodes(document, state)
  let node_order = document.document_order(node)
  let result : Array[@model.NodeId] = []
  if following {
    for candidate in all_nodes {
      state.charge()
      let kind = document.kind(candidate)
      if document.document_order(candidate) > node_order &&
        kind != Attribute &&
        kind != Namespace &&
        !is_ancestor(document, node, candidate, state) {
        result.push(candidate)
      }
    }
  } else {
    let mut index = all_nodes.length()
    while index > 0 {
      index = index - 1
      let candidate = all_nodes[index]
      state.charge()
      let kind = document.kind(candidate)
      if document.document_order(candidate) < node_order &&
        kind != Attribute &&
        kind != Namespace &&
        !is_ancestor(document, candidate, node, state) {
        result.push(candidate)
      }
    }
  }
  result
}

///|
fn axis_nodes(
  document : @model.Document,
  node : @model.NodeId,
  axis : XPathAxis,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  state.charge()
  match axis {
    Self => [node]
    Parent =>
      match document.parent(node) {
        Some(parent) => [parent]
        None => []
      }
    Child => document.children(node)
    Attribute =>
      if document.kind(node) == Element {
        document.attributes(node)
      } else {
        []
      }
    Namespace =>
      if document.kind(node) == Element {
        document.namespaces(node)
      } else {
        []
      }
    Descendant => collect_descendants(document, node, false, state)
    DescendantOrSelf => collect_descendants(document, node, true, state)
    Ancestor | AncestorOrSelf => {
      let result : Array[@model.NodeId] = []
      if axis == AncestorOrSelf {
        result.push(node)
      }
      let mut current = document.parent(node)
      while current is Some(parent) {
        state.charge()
        result.push(parent)
        current = document.parent(parent)
      }
      result
    }
    FollowingSibling => sibling_axis_nodes(document, node, true, state)
    PrecedingSibling => sibling_axis_nodes(document, node, false, state)
    Following => following_or_preceding_nodes(document, node, true, state)
    Preceding => following_or_preceding_nodes(document, node, false, state)
  }
}

///|
fn principal_kind(axis : XPathAxis) -> @model.NodeKind {
  match axis {
    Attribute => Attribute
    Namespace => Namespace
    _ => Element
  }
}

///|
fn matches_name_test(
  document : @model.Document,
  node : @model.NodeId,
  axis : XPathAxis,
  name_test : XPathNameTest,
) -> Bool raise @diagnostic.XPathError {
  if document.kind(node) != principal_kind(axis) {
    return false
  }
  match name_test {
    Any => true
    Expanded(expected) =>
      match document.name(node) {
        Some(actual) => actual == expected.expanded()
        None => false
      }
    NamespaceWildcard(expected) =>
      match document.name(node) {
        Some(actual) =>
          actual.namespace_uri() == expected.expanded().namespace_uri()
        None => false
      }
  }
}

///|
fn matches_node_test(
  document : @model.Document,
  node : @model.NodeId,
  axis : XPathAxis,
  node_test : XPathNodeTest,
) -> Bool raise @diagnostic.XPathError {
  let kind = document.kind(node)
  match node_test {
    Name(name_test) => matches_name_test(document, node, axis, name_test)
    Node => true
    Text => kind == Text
    Comment => kind == Comment
    ProcessingInstruction(target) =>
      if kind != ProcessingInstruction {
        false
      } else {
        match target {
          None => true
          Some(expected) =>
            match document.name(node) {
              Some(name) => name.local_name() == expected
              None => false
            }
        }
      }
  }
}

///|
fn predicate_keeps(
  predicate : XPathExpr,
  focus : @context.DynamicContext,
  state : EvaluationState,
) -> Bool raise @diagnostic.XPathError {
  let value = evaluate_expression(predicate, focus, state)
  match value {
    Number(position) => position == focus.position().to_double()
    _ => value.to_boolean()
  }
}

///|
fn apply_predicates(
  document : @model.Document,
  nodes : Array[@model.NodeId],
  predicates : Array[XPathExpr],
  context : @context.DynamicContext,
  state : EvaluationState,
) -> Array[@model.NodeId] raise @diagnostic.XPathError {
  let mut current = nodes
  for predicate in predicates {
    let kept : Array[@model.NodeId] = []
    let size = current.length()
    for index, node in current {
      state.charge()
      let focus = context.with_focus(node, index + 1, size)
      if predicate_keeps(predicate, focus, state) {
        kept.push(node)
      }
    }
    current = kept
    if current.length() > state.limits.max_nodeset_size() {
      raise LimitExceeded(phase=Evaluate, limit="max_nodeset_size")
    }
  }
  ignore(document)
  current
}

///|
fn apply_step(
  input : @value.NodeSet,
  step : XPathStep,
  context : @context.DynamicContext,
  state : EvaluationState,
) -> @value.NodeSet raise @diagnostic.XPathError {
  let document = input.document()
  let output : Array[@model.NodeId] = []
  for start in input.nodes() {
    state.charge()
    let selected : Array[@model.NodeId] = []
    for candidate in axis_nodes(document, start, step.axis, state) {
      state.charge()
      if matches_node_test(document, candidate, step.axis, step.node_test) {
        selected.push(candidate)
      }
    }
    let filtered = apply_predicates(
      document,
      selected,
      step.predicates,
      context,
      state,
    )
    for node in filtered {
      output.push(node)
      if output.length() > state.limits.max_nodeset_size() {
        raise LimitExceeded(phase=Evaluate, limit="max_nodeset_size")
      }
    }
  }
  limited_node_set(document, output, state)
}

///|
fn evaluate_path(
  path : XPathPath,
  context : @context.DynamicContext,
  state : EvaluationState,
) -> @value.XPathValue raise @diagnostic.XPathError {
  let mut current = match path.base {
    Root =>
      limited_node_set(context.document(), [context.document().root()], state)
    Context => context_as_nodes(context, state)
    Expression(base) => {
      let base_value = evaluate_expression(base, context, state)
      require_nodes(base_value, base.span, "path base")
    }
  }
  for step in path.steps {
    current = apply_step(current, step, context, state)
  }
  Nodes(current)
}

///|
fn evaluate_filter(
  base : XPathExpr,
  predicates : Array[XPathExpr],
  context : @context.DynamicContext,
  state : EvaluationState,
) -> @value.XPathValue raise @diagnostic.XPathError {
  let nodes = require_nodes(
    evaluate_expression(base, context, state),
    base.span,
    "filter expression",
  )
  let filtered = apply_predicates(
    nodes.document(),
    nodes.nodes(),
    predicates,
    context,
    state,
  )
  Nodes(limited_node_set(nodes.document(), filtered, state))
}

///|
fn node_strings(
  nodes : @value.NodeSet,
) -> Array[String] raise @diagnostic.XPathError {
  let values : Array[String] = []
  let document = nodes.document()
  for node in nodes.nodes() {
    values.push(document.string_value(node))
  }
  values
}

///|
fn any_string_pair(
  left : Array[String],
  right : Array[String],
  unequal : Bool,
) -> Bool {
  for left_value in left {
    for right_value in right {
      if unequal {
        if left_value != right_value {
          return true
        }
      } else if left_value == right_value {
        return true
      }
    }
  }
  false
}

///|
fn any_number_pair(
  left : Array[Double],
  right : Array[Double],
  operation : XPathBinaryOp,
) -> Bool {
  for left_value in left {
    for right_value in right {
      let matches = match operation {
        Equal => left_value == right_value
        NotEqual => left_value != right_value
        Less => left_value < right_value
        LessEqual => left_value <= right_value
        Greater => left_value > right_value
        GreaterEqual => left_value >= right_value
        _ => false
      }
      if matches {
        return true
      }
    }
  }
  false
}

///|
fn node_numbers(
  nodes : @value.NodeSet,
) -> Array[Double] raise @diagnostic.XPathError {
  let values : Array[Double] = []
  let document = nodes.document()
  for node in nodes.nodes() {
    values.push(
      (String(document.string_value(node)) : @value.XPathValue).to_number(),
    )
  }
  values
}

///|
fn equality_result(
  left : @value.XPathValue,
  right : @value.XPathValue,
  unequal : Bool,
) -> Bool raise @diagnostic.XPathError {
  match (left, right) {
    (Nodes(left_nodes), Nodes(right_nodes)) =>
      any_string_pair(
        node_strings(left_nodes),
        node_strings(right_nodes),
        unequal,
      )
    (Nodes(left_nodes), Boolean(right_value)) =>
      if unequal {
        (left_nodes.length() > 0) != right_value
      } else {
        (left_nodes.length() > 0) == right_value
      }
    (Boolean(left_value), Nodes(right_nodes)) =>
      if unequal {
        left_value != (right_nodes.length() > 0)
      } else {
        left_value == (right_nodes.length() > 0)
      }
    (Nodes(left_nodes), Number(right_value)) =>
      any_number_pair(
        node_numbers(left_nodes),
        [right_value],
        if unequal {
          NotEqual
        } else {
          Equal
        },
      )
    (Number(left_value), Nodes(right_nodes)) =>
      any_number_pair(
        [left_value],
        node_numbers(right_nodes),
        if unequal {
          NotEqual
        } else {
          Equal
        },
      )
    (Nodes(left_nodes), String(right_value)) =>
      any_string_pair(node_strings(left_nodes), [right_value], unequal)
    (String(left_value), Nodes(right_nodes)) =>
      any_string_pair([left_value], node_strings(right_nodes), unequal)
    (Boolean(left_value), other) =>
      if unequal {
        left_value != other.to_boolean()
      } else {
        left_value == other.to_boolean()
      }
    (other, Boolean(right_value)) =>
      if unequal {
        other.to_boolean() != right_value
      } else {
        other.to_boolean() == right_value
      }
    (Number(left_value), other) =>
      if unequal {
        left_value != other.to_number()
      } else {
        left_value == other.to_number()
      }
    (other, Number(right_value)) =>
      if unequal {
        other.to_number() != right_value
      } else {
        other.to_number() == right_value
      }
    (String(left_value), String(right_value)) =>
      if unequal {
        left_value != right_value
      } else {
        left_value == right_value
      }
  }
}

///|
fn relational_result(
  left : @value.XPathValue,
  right : @value.XPathValue,
  operation : XPathBinaryOp,
) -> Bool raise @diagnostic.XPathError {
  match (left, right) {
    (Nodes(left_nodes), Nodes(right_nodes)) =>
      any_number_pair(
        node_numbers(left_nodes),
        node_numbers(right_nodes),
        operation,
      )
    (Nodes(left_nodes), other) =>
      any_number_pair(node_numbers(left_nodes), [other.to_number()], operation)
    (other, Nodes(right_nodes)) =>
      any_number_pair([other.to_number()], node_numbers(right_nodes), operation)
    (left_value, right_value) =>
      any_number_pair(
        [left_value.to_number()],
        [right_value.to_number()],
        operation,
      )
  }
}

///|
fn evaluate_binary(
  operation : XPathBinaryOp,
  left : XPathExpr,
  right : XPathExpr,
  context : @context.DynamicContext,
  state : EvaluationState,
  span : @diagnostic.SourceSpan,
) -> @value.XPathValue raise @diagnostic.XPathError {
  match operation {
    Or => {
      let left_value = evaluate_expression(left, context, state)
      if left_value.to_boolean() {
        Boolean(true)
      } else {
        Boolean(evaluate_expression(right, context, state).to_boolean())
      }
    }
    And => {
      let left_value = evaluate_expression(left, context, state)
      if !left_value.to_boolean() {
        Boolean(false)
      } else {
        Boolean(evaluate_expression(right, context, state).to_boolean())
      }
    }
    Union => {
      let left_nodes = require_nodes(
        evaluate_expression(left, context, state),
        left.span,
        "union operand",
      )
      let right_nodes = require_nodes(
        evaluate_expression(right, context, state),
        right.span,
        "union operand",
      )
      let document = left_nodes.document()
      let combined = left_nodes.nodes()
      for node in right_nodes.nodes() {
        combined.push(node)
      }
      Nodes(limited_node_set(document, combined, state))
    }
    Equal =>
      Boolean(
        equality_result(
          evaluate_expression(left, context, state),
          evaluate_expression(right, context, state),
          false,
        ),
      )
    NotEqual =>
      Boolean(
        equality_result(
          evaluate_expression(left, context, state),
          evaluate_expression(right, context, state),
          true,
        ),
      )
    Less | LessEqual | Greater | GreaterEqual =>
      Boolean(
        relational_result(
          evaluate_expression(left, context, state),
          evaluate_expression(right, context, state),
          operation,
        ),
      )
    Add | Subtract | Multiply | Divide | Modulo => {
      let left_number = evaluate_expression(left, context, state).to_number()
      let right_number = evaluate_expression(right, context, state).to_number()
      let result = match operation {
        Add => left_number + right_number
        Subtract => left_number - right_number
        Multiply => left_number * right_number
        Divide => left_number / right_number
        Modulo => left_number % right_number
        _ => raise_evaluate(span, "unsupported XPath arithmetic operator")
      }
      Number(result)
    }
  }
}

///|
fn is_xml_space(value : Char) -> Bool {
  value == ' ' || value == '\t' || value == '\r' || value == '\n'
}

///|
fn split_xml_space(value : String) -> Array[String] {
  let result : Array[String] = []
  let current = StringBuilder()
  for character in value.to_array() {
    if is_xml_space(character) {
      if !current.to_string().is_empty() {
        result.push(current.to_string())
        current.reset()
      }
    } else {
      current.write_char(character)
    }
  }
  if !current.to_string().is_empty() {
    result.push(current.to_string())
  }
  result
}

///|
fn node_name_for_argument(
  arguments : Array[@value.XPathValue],
  context : @context.DynamicContext,
) -> (@model.Document, @model.NodeId)? raise @diagnostic.XPathError {
  if arguments.length() == 0 {
    return Some((context.document(), context.context_node()))
  }
  match arguments[0] {
    Nodes(nodes) =>
      match nodes.first() {
        Some(node) => Some((nodes.document(), node))
        None => None
      }
    _ =>
      raise Evaluate(
        span=None,
        message="node-name function requires a node-set",
      )
  }
}

///|
fn lexical_name(name : @model.QName) -> String {
  match name.prefix() {
    Some(prefix) => prefix + ":" + name.local_name()
    None => name.local_name()
  }
}

///|
fn string_before(value : String, delimiter : String) -> String {
  match value.find(delimiter) {
    Some(index) => value[0:index].to_owned()
    None => ""
  }
}

///|
fn string_after(value : String, delimiter : String) -> String {
  match value.find(delimiter) {
    Some(index) => value[index + delimiter.length():].to_owned()
    None => ""
  }
}

///|
fn xpath_round(value : Double) -> Double {
  if value.is_nan() || value.is_inf() {
    value
  } else if value >= -0.5 && value < 0.0 {
    -0.0
  } else {
    (value + 0.5).floor()
  }
}

///|
fn xpath_substring(value : String, start : Double, length : Double?) -> String {
  if start.is_nan() {
    return ""
  }
  let rounded_start = xpath_round(start)
  let rounded_length = match length {
    Some(value) =>
      if value.is_nan() {
        return ""
      } else {
        Some(xpath_round(value))
      }
    None => None
  }
  let end = match rounded_length {
    Some(value) => rounded_start + value
    None => @double.infinity
  }
  let output = StringBuilder()
  for index, character in value.to_array() {
    let position = (index + 1).to_double()
    if position >= rounded_start && position < end {
      output.write_char(character)
    }
  }
  output.to_string()
}

///|
fn normalize_space(value : String) -> String {
  let output = StringBuilder()
  let mut wrote_content = false
  let mut pending_space = false
  for character in value.to_array() {
    if is_xml_space(character) {
      if wrote_content {
        pending_space = true
      }
    } else {
      if pending_space {
        output.write_char(' ')
        pending_space = false
      }
      output.write_char(character)
      wrote_content = true
    }
  }
  output.to_string()
}

///|
fn character_index(values : Array[Char], needle : Char) -> Int? {
  for index, value in values {
    if value == needle {
      return Some(index)
    }
  }
  None
}

///|
fn translate_string(value : String, from : String, to : String) -> String {
  let from_chars = from.to_array()
  let to_chars = to.to_array()
  let output = StringBuilder()
  for character in value.to_array() {
    match character_index(from_chars, character) {
      None => output.write_char(character)
      Some(index) =>
        if index < to_chars.length() {
          output.write_char(to_chars[index])
        }
    }
  }
  output.to_string()
}

///|
fn ascii_fold(value : String) -> String {
  let output = StringBuilder()
  for character in value.to_array() {
    let code = character.to_int()
    if code >= 'A'.to_int() && code <= 'Z'.to_int() {
      output.write_char((code + 32).unsafe_to_char())
    } else {
      output.write_char(character)
    }
  }
  output.to_string()
}

///|
fn language_matches(actual : String, requested : String) -> Bool {
  let actual_folded = ascii_fold(actual)
  let requested_folded = ascii_fold(requested)
  actual_folded == requested_folded ||
  actual_folded.has_prefix(requested_folded + "-")
}

///|
const XML_NAMESPACE_URI : String = "http://www.w3.org/XML/1998/namespace"

///|
fn context_language(
  context : @context.DynamicContext,
) -> String? raise @diagnostic.XPathError {
  let document = context.document()
  let mut current = Some(context.context_node())
  while current is Some(node) {
    if document.kind(node) == Element {
      for attribute in document.attributes(node) {
        match document.name(attribute) {
          Some(name) =>
            if name.local_name() == "lang" &&
              name.namespace_uri() == Some(XML_NAMESPACE_URI) {
              return Some(document.string_value(attribute))
            }
          None => ()
        }
      }
    }
    current = document.parent(node)
  }
  None
}

///|
fn evaluate_core_function(
  core : XPathCoreFunction,
  arguments : Array[@value.XPathValue],
  context : @context.DynamicContext,
  state : EvaluationState,
  span : @diagnostic.SourceSpan,
) -> @value.XPathValue raise @diagnostic.XPathError {
  state.charge()
  match core {
    Id => {
      let tokens : Array[String] = []
      match arguments[0] {
        Nodes(nodes) =>
          for value in node_strings(nodes) {
            for token in split_xml_space(value) {
              tokens.push(token)
            }
          }
        other =>
          for token in split_xml_space(other.to_xpath_string()) {
            tokens.push(token)
          }
      }
      let nodes : Array[@model.NodeId] = []
      for token in tokens {
        state.charge()
        match context.document().element_by_id(token) {
          Some(node) => nodes.push(node)
          None => ()
        }
      }
      Nodes(limited_node_set(context.document(), nodes, state))
    }
    Last => Number(context.size().to_double())
    Position => Number(context.position().to_double())
    Count =>
      Number(require_nodes(arguments[0], span, "count").length().to_double())
    LocalName =>
      match node_name_for_argument(arguments, context) {
        Some((document, node)) =>
          match document.name(node) {
            Some(name) => String(name.local_name())
            None => String("")
          }
        None => String("")
      }
    NamespaceUri =>
      match node_name_for_argument(arguments, context) {
        Some((document, node)) =>
          match document.name(node) {
            Some(name) => String(name.namespace_uri().unwrap_or(""))
            None => String("")
          }
        None => String("")
      }
    Name =>
      match node_name_for_argument(arguments, context) {
        Some((document, node)) =>
          match document.name(node) {
            Some(name) => String(lexical_name(name))
            None => String("")
          }
        None => String("")
      }
    String =>
      if arguments.length() == 0 {
        String(context.document().string_value(context.context_node()))
      } else {
        String(arguments[0].to_xpath_string())
      }
    Concat => {
      let output = StringBuilder()
      for argument in arguments {
        output.write_string(argument.to_xpath_string())
      }
      String(output.to_string())
    }
    StartsWith =>
      Boolean(
        arguments[0]
        .to_xpath_string()
        .has_prefix(arguments[1].to_xpath_string()),
      )
    Contains =>
      Boolean(
        arguments[0].to_xpath_string().contains(arguments[1].to_xpath_string()),
      )
    SubstringBefore =>
      String(
        string_before(
          arguments[0].to_xpath_string(),
          arguments[1].to_xpath_string(),
        ),
      )
    SubstringAfter =>
      String(
        string_after(
          arguments[0].to_xpath_string(),
          arguments[1].to_xpath_string(),
        ),
      )
    Substring =>
      String(
        xpath_substring(
          arguments[0].to_xpath_string(),
          arguments[1].to_number(),
          if arguments.length() == 3 {
            Some(arguments[2].to_number())
          } else {
            None
          },
        ),
      )
    StringLength =>
      if arguments.length() == 0 {
        Number(
          context
          .document()
          .string_value(context.context_node())
          .to_array()
          .length()
          .to_double(),
        )
      } else {
        Number(arguments[0].to_xpath_string().to_array().length().to_double())
      }
    NormalizeSpace =>
      if arguments.length() == 0 {
        String(
          normalize_space(
            context.document().string_value(context.context_node()),
          ),
        )
      } else {
        String(normalize_space(arguments[0].to_xpath_string()))
      }
    Translate =>
      String(
        translate_string(
          arguments[0].to_xpath_string(),
          arguments[1].to_xpath_string(),
          arguments[2].to_xpath_string(),
        ),
      )
    Boolean => Boolean(arguments[0].to_boolean())
    Not => Boolean(!arguments[0].to_boolean())
    True => Boolean(true)
    False => Boolean(false)
    Lang =>
      match context_language(context) {
        Some(actual) =>
          Boolean(language_matches(actual, arguments[0].to_xpath_string()))
        None => Boolean(false)
      }
    Number =>
      if arguments.length() == 0 {
        Number(
          (
            String(context.document().string_value(context.context_node())) :
            @value.XPathValue).to_number(),
        )
      } else {
        Number(arguments[0].to_number())
      }
    Sum => {
      let mut sum = 0.0
      let nodes = require_nodes(arguments[0], span, "sum")
      let document = nodes.document()
      for node in nodes.nodes() {
        state.charge()
        sum = sum +
          (String(document.string_value(node)) : @value.XPathValue).to_number()
      }
      Number(sum)
    }
    Floor => Number(arguments[0].to_number().floor())
    Ceiling => Number(arguments[0].to_number().ceil())
    Round => Number(xpath_round(arguments[0].to_number()))
  }
}

///|
fn evaluate_function(
  call : XPathFunctionCall,
  context : @context.DynamicContext,
  state : EvaluationState,
  span : @diagnostic.SourceSpan,
) -> @value.XPathValue raise @diagnostic.XPathError {
  let values : Array[@value.XPathValue] = []
  for argument in call.arguments {
    values.push(evaluate_expression(argument, context, state))
  }
  match call.validated_core() {
    Some(core) => evaluate_core_function(core, values, context, state, span)
    None => raise_evaluate(span, "unvalidated XPath function call")
  }
}

///|
fn evaluate_expression(
  expression : XPathExpr,
  context : @context.DynamicContext,
  state : EvaluationState,
) -> @value.XPathValue raise @diagnostic.XPathError {
  state.charge()
  match expression.kind {
    Binary(operation, left, right) =>
      evaluate_binary(operation, left, right, context, state, expression.span)
    Unary(Negate, operand) =>
      Number(-evaluate_expression(operand, context, state).to_number())
    Literal(value) => String(value)
    Number(value) => Number(number_literal(value, expression.span))
    Variable(name) =>
      match context.resolve_variable(name.expanded()) {
        Some(value) => value
        None =>
          raise_evaluate(
            name.span,
            "unbound XPath variable '" + name.lexical + "'",
          )
      }
    Function(call) => evaluate_function(call, context, state, expression.span)
    Group(inner) => evaluate_expression(inner, context, state)
    Filter(base, predicates) =>
      evaluate_filter(base, predicates, context, state)
    Path(path) => evaluate_path(path, context, state)
  }
}

///|
pub fn evaluate(
  expression : CompiledXPath,
  context : @context.DynamicContext,
) -> @value.XPathValue raise @diagnostic.XPathError {
  let state = EvaluationState::{ limits: context.limits(), steps: 0 }
  evaluate_expression(expression.ir(), context, state)
}

///|
pub fn select(
  expression : CompiledXPath,
  context : @context.DynamicContext,
) -> @value.NodeSet raise @diagnostic.XPathError {
  match evaluate(expression, context) {
    Nodes(nodes) => nodes
    _ =>
      raise Evaluate(
        span=Some(expression.span()),
        message="XPath expression did not evaluate to a node-set",
      )
  }
}