lexer.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. use std::{io, io::Write, process, str::Chars};
  2. use termion::{color, style};
  3. #[derive(Hash, Eq, PartialEq, Clone, Debug)]
  4. pub enum TokenType {
  5. Symbol,
  6. String,
  7. LeftBrace,
  8. RightBrace,
  9. LeftParen,
  10. RightParen,
  11. Comma,
  12. Semicolon,
  13. Colon,
  14. Assign,
  15. }
  16. const SPECIAL_CHARS: [char; 7] = ['{', '}', '(', ')', ',', ';', '='];
  17. #[derive(Hash, Eq, PartialEq, Clone, Debug)]
  18. pub struct Token {
  19. pub token: String,
  20. pub token_type: TokenType,
  21. pub line: usize,
  22. pub column: usize,
  23. }
  24. impl Token {
  25. fn new(token: String, token_type: TokenType, line: usize, column: usize) -> Self {
  26. Token { token, token_type, line, column }
  27. }
  28. }
  29. pub struct Lexer<'a> {
  30. file: String,
  31. lines: Vec<String>,
  32. source: Chars<'a>,
  33. }
  34. impl<'a> Lexer<'a> {
  35. pub fn new(filename: &str, source: Chars<'a>) -> Self {
  36. // For nice error reporting, we'll load everything into a string
  37. // vector so we have references to lines.
  38. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  39. Lexer { file: filename.to_string(), lines, source }
  40. }
  41. pub fn lex(self) -> Vec<Token> {
  42. let mut tokens = vec![];
  43. let mut lineno = 1;
  44. let mut column = 0;
  45. // We use these as a buffer to keep strings and symbols
  46. let mut strbuf = String::new();
  47. let mut symbuf = String::new();
  48. // We use these to keep state when iterating
  49. let mut in_comment = false;
  50. let mut in_string = false;
  51. let mut in_symbol = false;
  52. #[allow(clippy::explicit_counter_loop)]
  53. for c in self.source.clone() {
  54. column += 1;
  55. if c == '\n' {
  56. if in_symbol {
  57. in_symbol = false;
  58. tokens.push(Token::new(
  59. symbuf.clone(),
  60. TokenType::Symbol,
  61. lineno,
  62. column - symbuf.len(),
  63. ));
  64. symbuf = String::new();
  65. }
  66. if in_string {
  67. // TODO: Allow newlines in strings?
  68. self.error(format!("Invalid ending in string `{}`", &strbuf), lineno, column);
  69. }
  70. in_comment = false;
  71. lineno += 1;
  72. column = 0;
  73. continue
  74. }
  75. if c == '#' || in_comment {
  76. if in_symbol {
  77. in_symbol = false;
  78. tokens.push(Token::new(
  79. symbuf.clone(),
  80. TokenType::Symbol,
  81. lineno,
  82. column - symbuf.len(),
  83. ));
  84. symbuf = String::new();
  85. }
  86. if in_string {
  87. strbuf.push(c);
  88. continue
  89. }
  90. in_comment = true;
  91. continue
  92. }
  93. if c.is_whitespace() {
  94. if in_symbol {
  95. in_symbol = false;
  96. tokens.push(Token::new(
  97. symbuf.clone(),
  98. TokenType::Symbol,
  99. lineno,
  100. column - symbuf.len(),
  101. ));
  102. symbuf = String::new();
  103. }
  104. continue
  105. }
  106. if !in_string && is_letter(c) {
  107. in_symbol = true;
  108. symbuf.push(c);
  109. continue
  110. }
  111. if in_string && is_letter(c) {
  112. strbuf.push(c);
  113. continue
  114. }
  115. if c == '"' && !in_string {
  116. if in_symbol {
  117. self.error(format!("Illegal char `{}` for symbol", c), lineno, column);
  118. }
  119. in_string = true;
  120. continue
  121. }
  122. if c == '"' && in_string {
  123. if strbuf.is_empty() {
  124. self.error(format!("Invalid ending in string `{}`", &strbuf), lineno, column);
  125. }
  126. in_string = false;
  127. tokens.push(Token::new(
  128. strbuf.clone(),
  129. TokenType::String,
  130. lineno,
  131. column - strbuf.len(),
  132. ));
  133. strbuf = String::new();
  134. continue
  135. }
  136. if SPECIAL_CHARS.contains(&c) {
  137. if in_symbol {
  138. in_symbol = false;
  139. tokens.push(Token::new(
  140. symbuf.clone(),
  141. TokenType::Symbol,
  142. lineno,
  143. column - symbuf.len(),
  144. ));
  145. symbuf = String::new();
  146. }
  147. match c {
  148. '{' => {
  149. tokens.push(Token::new(
  150. "{".to_string(),
  151. TokenType::LeftBrace,
  152. lineno,
  153. column,
  154. ));
  155. continue
  156. }
  157. '}' => {
  158. tokens.push(Token::new(
  159. "}".to_string(),
  160. TokenType::RightBrace,
  161. lineno,
  162. column,
  163. ));
  164. continue
  165. }
  166. '(' => {
  167. tokens.push(Token::new(
  168. "(".to_string(),
  169. TokenType::LeftParen,
  170. lineno,
  171. column,
  172. ));
  173. continue
  174. }
  175. ')' => {
  176. tokens.push(Token::new(
  177. ")".to_string(),
  178. TokenType::RightParen,
  179. lineno,
  180. column,
  181. ));
  182. continue
  183. }
  184. ',' => {
  185. tokens.push(Token::new(",".to_string(), TokenType::Comma, lineno, column));
  186. continue
  187. }
  188. ';' => {
  189. tokens.push(Token::new(
  190. ";".to_string(),
  191. TokenType::Semicolon,
  192. lineno,
  193. column,
  194. ));
  195. continue
  196. }
  197. '=' => {
  198. tokens.push(Token::new("=".to_string(), TokenType::Assign, lineno, column));
  199. continue
  200. }
  201. _ => self.error(format!("Invalid token `{}`", c), lineno, column - 1),
  202. }
  203. continue
  204. }
  205. self.error(format!("Invalid token `{}`", c), lineno, column - 1);
  206. }
  207. tokens
  208. }
  209. fn error(&self, msg: String, ln: usize, col: usize) {
  210. let err_msg = format!("{} (line {}, column {})", msg, ln, col);
  211. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  212. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  213. let caret = format!("{:width$}^", "", width = pad);
  214. let msg = format!("{}\n{}\n{}\n", err_msg, dbg_msg, caret);
  215. Lexer::abort(&msg);
  216. }
  217. fn abort(msg: &str) {
  218. let stderr = io::stderr();
  219. let mut handle = stderr.lock();
  220. write!(
  221. handle,
  222. "{}{}Lexer error:{} {}",
  223. style::Bold,
  224. color::Fg(color::Red),
  225. style::Reset,
  226. msg,
  227. )
  228. .unwrap();
  229. handle.flush().unwrap();
  230. process::exit(1);
  231. }
  232. }
  233. fn is_letter(ch: char) -> bool {
  234. ('a'..='z').contains(&ch) || ('A'..='Z').contains(&ch) || ch == '_'
  235. }
  236. /*
  237. fn is_digit(ch: char) -> bool {
  238. ('0'..'9').contains(&ch)
  239. }
  240. */