lexer.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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) || is_digit(c)) {
  112. strbuf.push(c);
  113. continue
  114. }
  115. if in_symbol && is_digit(c) {
  116. symbuf.push(c);
  117. continue
  118. }
  119. if c == '"' && !in_string {
  120. if in_symbol {
  121. self.error(format!("Illegal char `{}` for symbol", c), lineno, column);
  122. }
  123. in_string = true;
  124. continue
  125. }
  126. if c == '"' && in_string {
  127. if strbuf.is_empty() {
  128. self.error(format!("Invalid ending in string `{}`", &strbuf), lineno, column);
  129. }
  130. in_string = false;
  131. tokens.push(Token::new(
  132. strbuf.clone(),
  133. TokenType::String,
  134. lineno,
  135. column - strbuf.len(),
  136. ));
  137. strbuf = String::new();
  138. continue
  139. }
  140. if SPECIAL_CHARS.contains(&c) {
  141. if in_symbol {
  142. in_symbol = false;
  143. tokens.push(Token::new(
  144. symbuf.clone(),
  145. TokenType::Symbol,
  146. lineno,
  147. column - symbuf.len(),
  148. ));
  149. symbuf = String::new();
  150. }
  151. match c {
  152. '{' => {
  153. tokens.push(Token::new(
  154. "{".to_string(),
  155. TokenType::LeftBrace,
  156. lineno,
  157. column,
  158. ));
  159. continue
  160. }
  161. '}' => {
  162. tokens.push(Token::new(
  163. "}".to_string(),
  164. TokenType::RightBrace,
  165. lineno,
  166. column,
  167. ));
  168. continue
  169. }
  170. '(' => {
  171. tokens.push(Token::new(
  172. "(".to_string(),
  173. TokenType::LeftParen,
  174. lineno,
  175. column,
  176. ));
  177. continue
  178. }
  179. ')' => {
  180. tokens.push(Token::new(
  181. ")".to_string(),
  182. TokenType::RightParen,
  183. lineno,
  184. column,
  185. ));
  186. continue
  187. }
  188. ',' => {
  189. tokens.push(Token::new(",".to_string(), TokenType::Comma, lineno, column));
  190. continue
  191. }
  192. ';' => {
  193. tokens.push(Token::new(
  194. ";".to_string(),
  195. TokenType::Semicolon,
  196. lineno,
  197. column,
  198. ));
  199. continue
  200. }
  201. '=' => {
  202. tokens.push(Token::new("=".to_string(), TokenType::Assign, lineno, column));
  203. continue
  204. }
  205. _ => self.error(format!("Invalid token `{}`", c), lineno, column - 1),
  206. }
  207. continue
  208. }
  209. self.error(format!("Invalid token `{}`", c), lineno, column - 1);
  210. }
  211. tokens
  212. }
  213. fn error(&self, msg: String, ln: usize, col: usize) {
  214. let err_msg = format!("{} (line {}, column {})", msg, ln, col);
  215. let dbg_msg = format!("{}:{}:{}: {}", self.file, ln, col, self.lines[ln - 1]);
  216. let pad = dbg_msg.split(": ").next().unwrap().len() + col + 2;
  217. let caret = format!("{:width$}^", "", width = pad);
  218. let msg = format!("{}\n{}\n{}\n", err_msg, dbg_msg, caret);
  219. Lexer::abort(&msg);
  220. }
  221. fn abort(msg: &str) {
  222. let stderr = io::stderr();
  223. let mut handle = stderr.lock();
  224. write!(
  225. handle,
  226. "{}{}Lexer error:{} {}",
  227. style::Bold,
  228. color::Fg(color::Red),
  229. style::Reset,
  230. msg,
  231. )
  232. .unwrap();
  233. handle.flush().unwrap();
  234. process::exit(1);
  235. }
  236. }
  237. fn is_letter(ch: char) -> bool {
  238. ('a'..='z').contains(&ch) || ('A'..='Z').contains(&ch) || ch == '_'
  239. }
  240. fn is_digit(ch: char) -> bool {
  241. ('0'..'9').contains(&ch)
  242. }