///|
#derive(Eq)
priv enum PathNode {
  Root(String?)
  Index(PathNode, Int32)
  Key(PathNode, String)
}

///|
/// The place of a value in a payload, for decode errors. The root of a whole
/// payload is `$`; the arguments of an invocation are `arguments`. An index adds
/// `[n]` and a property adds `.name`, for example `arguments[0].userName`.
#derive(Eq)
pub struct Path {
  priv node : PathNode
}

///|
pub extend Path with Eq::{equal, not_equal}

///|
/// The root of a payload, written `$`.
pub fn Path::root() -> Path {
  { node: Root(None), }
}

///|
/// A root with the name `name`, for example `arguments` or `result`.
pub fn Path::named(name : String) -> Path {
  { node: Root(Some(name)), }
}

///|
/// The path of the item at `index` of the array at `self`.
pub fn Path::index(self : Path, index : Int32) -> Path {
  { node: Index(self.node, index), }
}

///|
/// The path of the property `key` of the object at `self`.
pub fn Path::key(self : Path, key : String) -> Path {
  { node: Key(self.node, key), }
}

///|
fn write_node(node : PathNode, logger : &Logger) -> Unit {
  match node {
    Root(None) => logger.write_string("$")
    Root(Some(name)) => logger.write_string(name)
    Index(parent, index) => {
      write_node(parent, logger)
      logger.write_string("[\{index}]")
    }
    Key(parent, key) => {
      write_node(parent, logger)
      logger.write_char('.')
      logger.write_string(key)
    }
  }
}

///|
pub impl Show for Path with fn output(self, logger) {
  write_node(self.node, logger)
}

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

///|
pub impl @debug.Debug for Path with fn to_repr(self) {
  @debug.Repr(self.to_string())
}

///|
pub extend Path with @debug.Debug::{to_repr}