use crate::common::*;
use std::{borrow::Cow, mem};
macro_rules! tree {
  {
    ($($child:tt)*)
  } => {
    $crate::tree::Tree::List(vec![$(tree!($child),)*])
  };
  {
    $atom:ident
  } => {
    $crate::tree::Tree::atom(stringify!($atom))
  };
  {
    $atom:literal
  } => {
    $crate::tree::Tree::atom(format!("\"{}\"", $atom))
  };
  {
    #
  } => {
    $crate::tree::Tree::atom("#")
  };
  {
    +
  } => {
    $crate::tree::Tree::atom("+")
  };
  {
    *
  } => {
    $crate::tree::Tree::atom("*")
  };
  {
    &&
  } => {
    $crate::tree::Tree::atom("&&")
  };
  {
    ==
  } => {
    $crate::tree::Tree::atom("==")
  };
  {
    !=
  } => {
    $crate::tree::Tree::atom("!=")
  };
}
#[derive(Debug, PartialEq)]
pub(crate) enum Tree<'text> {
    Atom(Cow<'text, str>),
    List(Vec<Tree<'text>>),
}
impl<'text> Tree<'text> {
    pub(crate) fn atom(text: impl Into<Cow<'text, str>>) -> Tree<'text> {
    Tree::Atom(text.into())
  }
    pub(crate) fn list(children: impl IntoIterator<Item = Tree<'text>>) -> Tree<'text> {
    Tree::List(children.into_iter().collect())
  }
    pub(crate) fn string(contents: impl AsRef<str>) -> Tree<'text> {
    Tree::atom(format!("\"{}\"", contents.as_ref()))
  }
    pub(crate) fn push(self, tree: impl Into<Tree<'text>>) -> Tree<'text> {
    match self {
      Tree::List(mut children) => {
        children.push(tree.into());
        Tree::List(children)
      }
      Tree::Atom(text) => Tree::List(vec![Tree::Atom(text), tree.into()]),
    }
  }
      pub(crate) fn extend<I, T>(self, tail: I) -> Tree<'text>
  where
    I: IntoIterator<Item = T>,
    T: Into<Tree<'text>>,
  {
        let mut head = match self {
      Tree::List(children) => children,
      Tree::Atom(text) => vec![Tree::Atom(text)],
    };
    for child in tail {
      head.push(child.into());
    }
    Tree::List(head)
  }
    pub(crate) fn push_mut(&mut self, tree: impl Into<Tree<'text>>) {
    *self = mem::replace(self, Tree::List(Vec::new())).push(tree.into());
  }
}
impl Display for Tree<'_> {
  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
    match self {
      Tree::List(children) => {
        write!(f, "(")?;
        for (i, child) in children.iter().enumerate() {
          if i > 0 {
            write!(f, " ")?;
          }
          write!(f, "{}", child)?;
        }
        write!(f, ")")
      }
      Tree::Atom(text) => write!(f, "{}", text),
    }
  }
}
impl<'text, T> From<T> for Tree<'text>
where
  T: Into<Cow<'text, str>>,
{
  fn from(text: T) -> Tree<'text> {
    Tree::Atom(text.into())
  }
}