awkward but sorta works

parse-tree
Jordan Orelli 2 years ago
parent 7abb60a3bc
commit 0befb4e48a

@ -1,5 +1,7 @@
use log::debug; use log::debug;
use std::{ use std::{
fmt,
ops::Deref,
cell::RefCell, cell::RefCell,
rc::Rc, rc::Rc,
}; };
@ -129,14 +131,23 @@ impl<'text> Lexer<'text> {
// } // }
// } // }
#[derive(Debug, PartialEq, Clone)] #[derive(PartialEq, Clone)]
pub enum Element { pub enum Element {
Empty, Empty,
Command(String), Command(String),
Literal(String), Literal(String),
} }
#[derive(Debug)] impl fmt::Debug for Element {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
match self {
Element::Empty => write!(f, "()"),
Element::Command(cmd) => write!(f, "cmd<{}>", cmd),
Element::Literal(lit) => write!(f, "lit<{}>", lit),
}
}
}
pub struct Node { pub struct Node {
pub elem: Element, pub elem: Element,
pub parent: Option<Rc<RefCell<Node>>>, pub parent: Option<Rc<RefCell<Node>>>,
@ -169,7 +180,20 @@ impl Node {
} }
} }
#[derive(Debug)] impl fmt::Debug for Node {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{:?}", self.elem)?;
if self.children.len() > 0 {
write!(f, "[")?;
for child in self.children.iter() {
write!(f, "{:?}", child.borrow())?;
}
write!(f, "]")?;
}
Ok(())
}
}
pub struct Tree { pub struct Tree {
target: Rc<RefCell<Node>>, target: Rc<RefCell<Node>>,
} }
@ -236,34 +260,34 @@ impl Tree {
fn children(&self) -> ChildIter { fn children(&self) -> ChildIter {
ChildIter { ChildIter {
target: Rc::clone(&self.target), parent: Rc::clone(&self.target),
idx: 0, idx: 0,
last: None,
} }
} }
} }
pub struct ChildIter<'n> { impl fmt::Debug for Tree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{:?}", self.target.borrow())
}
}
pub struct ChildIter {
/// pointer to the node in the tree whose children we are looking at. /// pointer to the node in the tree whose children we are looking at.
target: Rc<RefCell<Node>>, parent: Rc<RefCell<Node>>,
idx: usize, idx: usize,
last: Option<&'n Node>,
} }
impl <'n> Iterator for ChildIter<'n> { impl Iterator for ChildIter {
type Item = &'n Node; type Item = Tree;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.idx >= self.target.borrow().children.len() { if self.idx >= self.parent.borrow().children.len() {
None None
} else { } else {
let child = Rc::clone(&self.target.borrow().children[self.idx]); let child = Rc::clone(&self.parent.borrow().children[self.idx]);
self.idx += 1; self.idx += 1;
self.last = Some(&child.as_ref().borrow()); Some(Tree{target: child})
None
//Some(&child.as_ref().borrow())
//Some(&*child.borrow())
} }
} }
} }
@ -359,8 +383,8 @@ mod tests {
ident("one"); ident("one");
two_tokens: two_tokens:
"one two" "ls one two"
ident("one") ident("two"); ident("ls") ident("one") ident("two");
leading_whitespace: leading_whitespace:
" one" " one"
@ -421,37 +445,19 @@ mod tests {
assert_eq!(tree.peek(), Element::Command(String::from("ls"))); assert_eq!(tree.peek(), Element::Command(String::from("ls")));
} }
#[test] #[test]
fn test_parse() { fn parse_args() {
let res = parse("ls one two"); let res = parse("ls one two three");
assert!(res.is_ok()); assert!(res.is_ok());
let tree = res.unwrap(); let tree = res.unwrap();
assert_eq!(tree.peek(), Element::Command(String::from("ls"))); assert_eq!(tree.peek(), Element::Command(String::from("ls")));
assert_eq!(tree.children().count(), 2); assert_eq!(tree.children().count(), 3);
let args = tree.children();
// assert_eq!(args.next().unwrap(), Element::Literal(String::from("one")));
}
/* let mut args = tree.children();
#[test] assert_eq!(args.next().unwrap().peek(), Element::Literal(String::from("one")));
fn tree_command() { assert_eq!(args.next().unwrap().peek(), Element::Literal(String::from("two")));
/* assert_eq!(args.next().unwrap().peek(), Element::Literal(String::from("three")));
Command(ls) assert!(args.next().is_none());
Literal(.)
*/
let root = Tree::new()
.push(Element::Command(String::from("ls")))
.push(Element::Literal(String::from(".")))
.root();
assert!(root.is_root());
assert_eq!(root.children().count(), 1);
// assert_eq!(root.elem, Element::Command(String::from("ls")));
// assert_eq!(root.children.len(), 1);
// assert_eq!(root.children[0].borrow(), Element::Literal(String::from(".")));
} }
*/
} }

@ -2,10 +2,10 @@ use crate::{
ext::{Command, Echo, Printenv, Tail, Which}, ext::{Command, Echo, Printenv, Tail, Which},
input, input,
line::Line, line::Line,
parse::Node,
log::*, log::*,
output, output,
// parse::parse, // parse::parse,
parse::{Element, Node},
}; };
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
@ -99,17 +99,24 @@ impl Shell {
} }
pub fn exec(&mut self, root: Node) -> Result<bool> { pub fn exec(&mut self, root: Node) -> Result<bool> {
// match &tree.elem { match root.elem {
// Node::Command(name) => { Element::Empty => Ok(true),
// let args: Vec<&str> = tree.children.iter().map(|t| match &t.elem { Element::Command(cmd) => {
// Node::Literal(arg) => arg.as_str(), let args: Vec<String> = root
// _ => todo!(), .children
// }).collect(); .iter()
// self.eval(name.to_string(), args)?; .map(|node| match &node.borrow().elem {
// }, Element::Literal(v) => v.clone(),
// _ => todo!(), _ => todo!(),
// } })
Ok(true) .collect();
self.eval(
cmd.to_string(),
args.iter().map(|arg| arg.as_str()).collect(),
)
}
Element::Literal(_) => todo!(),
}
} }
pub fn eval(&mut self, cmd: String, args: Vec<&str>) -> Result<bool> { pub fn eval(&mut self, cmd: String, args: Vec<&str>) -> Result<bool> {

Loading…
Cancel
Save