Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. #[derive(Clone, Debug)]
  2. enum Lex {
  3. LeftParen,
  4. Symbol(String),
  5. RightParen,
  6. }
  7.  
  8. #[derive(Debug)]
  9.  
  10. enum Ast {
  11. Leaf(String),
  12. List(Vec<Ast>),
  13. }
  14.  
  15. use Lex::*;
  16. fn parse(lexemes: Box<Iterator<Item = Lex>>) -> (Option<(Ast, Box<Iterator<Item = Lex>>)>) {
  17. println!("parse");
  18. let mut result = Vec::new();
  19. let mut lexemes = lexemes;
  20. while let Some(l) = lexemes.next() {
  21. println!("l = {:?}", l);
  22. match l {
  23. LeftParen => {
  24. let rest = parse(lexemes).unwrap();
  25. result.push(rest.0);
  26. lexemes = rest.1
  27. }
  28. Symbol(x) => {
  29. result.push(Ast::Leaf(x));
  30. }
  31. RightParen => {
  32. return Some((Ast::List(result), lexemes));
  33. }
  34. }
  35. }
  36. if result.len() == 1 {
  37. Some((result.pop().unwrap(), lexemes))
  38. } else {
  39. None
  40. }
  41. }
  42. use std::mem::replace;
  43. fn parse2(lexemes: Box<Iterator<Item = Lex>>) -> Ast {
  44. let mut stack = Vec::new();
  45.  
  46. let mut result = Vec::new();
  47. let mut lexemes = lexemes;
  48. while let Some(l) = lexemes.next() {
  49. println!("l = {:?}", l);
  50. match l {
  51. LeftParen => {
  52. stack.push(replace(&mut result, Vec::new()));
  53. }
  54. Symbol(x) => {
  55. result.push(Ast::Leaf(x));
  56. }
  57. RightParen => {
  58. let old_result = stack.pop().unwrap();
  59. let last_paren = replace(&mut result, old_result);
  60. result.push(Ast::List(last_paren ))
  61. }
  62. }
  63. }
  64. result.pop().unwrap()
  65. }
  66.  
  67.  
  68. fn main() {
  69. //(sresh 1 (+ 1 2) 3 7)
  70. let x = vec![
  71. LeftParen,
  72. Symbol("sresh".to_string()),
  73. LeftParen,
  74. Symbol("+".to_string()),
  75. Symbol("1".to_string()),
  76. Symbol("2".to_string()),
  77. RightParen,
  78. Symbol("3".to_string()),
  79. Symbol("7".to_string()),
  80. RightParen,
  81. ];
  82. println!("new: {:?}", parse(Box::new(x.clone().into_iter())).unwrap().0);
  83.  
  84. println!("new: {:?}", parse2(Box::new(x.into_iter())))
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement