| 1 | use std::collections::VecDeque; |
| 2 | use std::str::Chars; |
| 3 | |
| 4 | pub struct Lex<'a> { |
| 5 | pub lineno: u32, |
| 6 | pub instream: Chars<'a>, |
| 7 | pub pushback: VecDeque<String>, |
| 8 | } |
| 9 | |
| 10 | impl<'a> Lex<'a> { |
| 11 | pub fn new(content: &'a str) -> Self { |
| 12 | Lex { |
| 13 | lineno: 1, |
| 14 | instream: content.chars(), |
| 15 | pushback: VecDeque::new(), |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | pub fn read_char(&mut self) -> Option<char> { |
| 20 | let ch = self.instream.next(); |
| 21 | if ch == Some('\n') { |
| 22 | self.lineno += 1; |
| 23 | } |
| 24 | ch |
| 25 | } |
| 26 | |
| 27 | pub fn read_line(&mut self) -> String { |
| 28 | let mut s = String::new(); |
| 29 | for ch in &mut self.instream { |
| 30 | if ch == '\n' { |
| 31 | return s; |
| 32 | } |
| 33 | s.push(ch); |
| 34 | } |
| 35 | s |
| 36 | } |
| 37 | |
| 38 | pub fn get_token(&mut self) -> String { |
| 39 | let p = self.pushback.pop_front(); |
| 40 | if let Some(x) = p { |
| 41 | return x; |
| 42 | } |
| 43 | let mut token = String::new(); |
| 44 | |
| 45 | while let Some(ch) = self.read_char() { |
| 46 | match ch { |
| 47 | '\n' | '\t' | '\r' | ' ' => { |
| 48 | continue; |
| 49 | } |
| 50 | '"' => { |
| 51 | while let Some(ch) = self.read_char() { |
| 52 | match ch { |
| 53 | '"' => { |
| 54 | return token; |
| 55 | } |
| 56 | '\\' => { |
| 57 | token.push(self.read_char().unwrap_or(' ')); |
| 58 | } |
| 59 | _ => { |
| 60 | token.push(ch); |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | _ => { |
| 66 | let c = if ch == '\\' { |
| 67 | self.read_char().unwrap_or(' ') |
| 68 | } else { |
| 69 | ch |
| 70 | }; |
| 71 | token.push(c); |
| 72 | while let Some(ch) = self.read_char() { |
| 73 | let c = match ch { |
| 74 | '\n' | '\t' | '\r' | ' ' => { |
| 75 | return token; |
| 76 | } |
| 77 | '\\' => self.read_char().unwrap_or(' '), |
| 78 | _ => ch, |
| 79 | }; |
| 80 | token.push(c); |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | token |
| 86 | } |
| 87 | |
| 88 | pub fn push_token(&mut self, token: &str) { |
| 89 | self.pushback.push_back(token.to_owned()); |
| 90 | } |
| 91 | } |