Advertisement
Guest User

Untitled

a guest
May 24th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. // syntax parse tree example
  2. // will parse (hello (foo) doo) trees
  3. #[derive(Debug)]
  4. enum ParseNode {
  5. Error(String),
  6. Word(String),
  7. Lst(Vec<ParseNode>)
  8. }
  9.  
  10. impl ParseNode {
  11.  
  12. pub fn parse(text:String) -> Self {
  13. if text.len() == 0 {
  14. ParseNode::Error(String::from("Cannot parse empty string."));
  15. }
  16. ParseNode::parse_val(&mut text.chars())
  17. }
  18.  
  19. fn parse_val(context:&mut std::str::Chars) -> Self {
  20. //unimplemented!()
  21. loop {
  22. match context.next() {
  23. Some(ch) => match ch {
  24. // Proceed through whitespace
  25. ' ' | '\n' | '\t' => (),
  26. '(' => break ParseNode::parse_lst(context),
  27. _ => break ParseNode::Error(format!("Expected list with '(' , got '{}'", ch))
  28. },
  29. None => break ParseNode::Error(String::from("Encountered empty text at top parsing function"))
  30. }
  31. }
  32. }
  33.  
  34. fn parse_lst(context:&mut std::str::Chars) -> Self {
  35. let mut arr:Vec<ParseNode> = vec![];
  36. loop {
  37. match context.next() {
  38. Some(ch) => match ch {
  39. ' ' | '\n' | '\t' => (),
  40. 'a' ... 'z' => arr.push(ParseNode::parse_word(context)),
  41. '(' => arr.push(ParseNode::parse_lst(context)),
  42. // end of list found
  43. ')' => break,
  44. _ => return ParseNode::Error(format!("Expected 'a' ... 'z', got '{}'", ch))
  45. },
  46. None => break
  47. }
  48. }
  49. ParseNode::Lst(arr)
  50. }
  51.  
  52. fn parse_word(context:&mut std::str::Chars) -> Self {
  53. let mut word = String::new();
  54. loop {
  55. match context.next() {
  56. Some(ch) => match ch {
  57. 'a' ... 'z' => word.push(ch),
  58. ' ' | '\n' | '\t' => break,
  59. _ => return ParseNode::Error(format!("Expected 'a' ... 'z', got '{}'", ch))
  60. },
  61. None => break
  62. }
  63. }
  64. ParseNode::Word(word)
  65. }
  66.  
  67. }
  68.  
  69.  
  70. fn main() {
  71. let code = "( a b c )";
  72. let text = String::from(code);
  73. let tree = ParseNode::parse(text);
  74. println!("{:?}", tree);
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement