use id_tree::{
InsertBehavior::{AsRoot, UnderNode},
Node, NodeId, Tree, TreeBuilder,
};
use super::{super::atomdict::AtomDict, node::ASTNode, node::NodeType, treebuilder::F};
use crate::public::{failures::ErrorCases, traits::CheckedType};
pub struct ASTTree<T: CheckedType> {
tree: Tree<ASTNode<T>>,
nodes: Vec<NodeId>,
index: usize,
}
impl<T: CheckedType> ASTTree<T> {
pub fn new() -> Self {
let mut tree: Tree<ASTNode<T>> = TreeBuilder::new().build();
let mut nodes: Vec<NodeId> = Vec::new();
nodes.push(
tree.insert(Node::new(ASTNode::new(NodeType::MoleculeGroup)), AsRoot)
.unwrap(), );
Self {
tree,
nodes,
index: 0,
}
}
pub fn get_index(&self) -> usize {
self.index
}
pub fn change_index(&mut self, index: usize) {
self.index = index;
}
pub fn new_node(&mut self, nodetype: NodeType<T>) -> Result<usize, ErrorCases> {
self.nodes.push(
self.tree
.insert(
Node::new(ASTNode::new(nodetype)),
UnderNode(&self.nodes[self.index]),
)
.map_err(F)?,
);
Ok(self.nodes.len() - 1)
}
pub fn to_atomdict(&self) -> Result<AtomDict<T>, ErrorCases> {
self.tree
.get(&self.tree.root_node_id().unwrap())
.map_err(F)?
.data()
.to_atomdict(&self.tree.root_node_id().unwrap(), &self.tree)
}
}