Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // syntax parse tree example
- // will parse (hello (foo) doo) trees
- #[derive(Debug)]
- enum ParseNode {
- Error(String),
- Word(String),
- Lst(Vec<ParseNode>)
- }
- impl ParseNode {
- pub fn parse(text:String) -> Self {
- if text.len() == 0 {
- ParseNode::Error(String::from("Cannot parse empty string."));
- }
- ParseNode::parse_val(&mut text.chars())
- }
- fn parse_val(context:&mut std::str::Chars) -> Self {
- //unimplemented!()
- loop {
- match context.next() {
- Some(ch) => match ch {
- // Proceed through whitespace
- ' ' | '\n' | '\t' => (),
- '(' => break ParseNode::parse_lst(context),
- _ => break ParseNode::Error(format!("Expected list with '(' , got '{}'", ch))
- },
- None => break ParseNode::Error(String::from("Encountered empty text at top parsing function"))
- }
- }
- }
- fn parse_lst(context:&mut std::str::Chars) -> Self {
- let mut arr:Vec<ParseNode> = vec![];
- loop {
- match context.next() {
- Some(ch) => match ch {
- ' ' | '\n' | '\t' => (),
- 'a' ... 'z' => arr.push(ParseNode::parse_word(context)),
- '(' => arr.push(ParseNode::parse_lst(context)),
- // end of list found
- ')' => break,
- _ => return ParseNode::Error(format!("Expected 'a' ... 'z', got '{}'", ch))
- },
- None => break
- }
- }
- ParseNode::Lst(arr)
- }
- fn parse_word(context:&mut std::str::Chars) -> Self {
- let mut word = String::new();
- loop {
- match context.next() {
- Some(ch) => match ch {
- 'a' ... 'z' => word.push(ch),
- ' ' | '\n' | '\t' => break,
- _ => return ParseNode::Error(format!("Expected 'a' ... 'z', got '{}'", ch))
- },
- None => break
- }
- }
- ParseNode::Word(word)
- }
- }
- fn main() {
- let code = "( a b c )";
- let text = String::from(code);
- let tree = ParseNode::parse(text);
- println!("{:?}", tree);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement