lexer.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. use std::str::Chars;
  2. use super::error::ErrorEmitter;
  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. source: Chars<'a>,
  31. error: ErrorEmitter,
  32. }
  33. impl<'a> Lexer<'a> {
  34. pub fn new(filename: &str, source: Chars<'a>) -> Self {
  35. // For nice error reporting, we'll load everything into a string
  36. // vector so we have references to lines.
  37. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  38. let error = ErrorEmitter::new("Lexer", filename, lines);
  39. Self { source, error }
  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.emit(
  69. format!("Invalid ending in string `{}`", &strbuf),
  70. lineno,
  71. column,
  72. );
  73. }
  74. in_comment = false;
  75. lineno += 1;
  76. column = 0;
  77. continue
  78. }
  79. if c == '#' || in_comment {
  80. if in_symbol {
  81. in_symbol = false;
  82. tokens.push(Token::new(
  83. symbuf.clone(),
  84. TokenType::Symbol,
  85. lineno,
  86. column - symbuf.len(),
  87. ));
  88. symbuf = String::new();
  89. }
  90. if in_string {
  91. strbuf.push(c);
  92. continue
  93. }
  94. in_comment = true;
  95. continue
  96. }
  97. if c.is_whitespace() {
  98. if in_symbol {
  99. in_symbol = false;
  100. tokens.push(Token::new(
  101. symbuf.clone(),
  102. TokenType::Symbol,
  103. lineno,
  104. column - symbuf.len(),
  105. ));
  106. symbuf = String::new();
  107. }
  108. continue
  109. }
  110. if !in_string && is_letter(c) {
  111. in_symbol = true;
  112. symbuf.push(c);
  113. continue
  114. }
  115. if in_string && (is_letter(c) || is_digit(c)) {
  116. strbuf.push(c);
  117. continue
  118. }
  119. if in_symbol && is_digit(c) {
  120. symbuf.push(c);
  121. continue
  122. }
  123. if c == '"' && !in_string {
  124. if in_symbol {
  125. self.error.emit(format!("Illegal char `{}` for symbol", c), lineno, column);
  126. }
  127. in_string = true;
  128. continue
  129. }
  130. if c == '"' && in_string {
  131. if strbuf.is_empty() {
  132. self.error.emit(
  133. format!("Invalid ending in string `{}`", &strbuf),
  134. lineno,
  135. column,
  136. );
  137. }
  138. in_string = false;
  139. tokens.push(Token::new(
  140. strbuf.clone(),
  141. TokenType::String,
  142. lineno,
  143. column - strbuf.len(),
  144. ));
  145. strbuf = String::new();
  146. continue
  147. }
  148. if SPECIAL_CHARS.contains(&c) {
  149. if in_symbol {
  150. in_symbol = false;
  151. tokens.push(Token::new(
  152. symbuf.clone(),
  153. TokenType::Symbol,
  154. lineno,
  155. column - symbuf.len(),
  156. ));
  157. symbuf = String::new();
  158. }
  159. match c {
  160. '{' => {
  161. tokens.push(Token::new(
  162. "{".to_string(),
  163. TokenType::LeftBrace,
  164. lineno,
  165. column,
  166. ));
  167. continue
  168. }
  169. '}' => {
  170. tokens.push(Token::new(
  171. "}".to_string(),
  172. TokenType::RightBrace,
  173. lineno,
  174. column,
  175. ));
  176. continue
  177. }
  178. '(' => {
  179. tokens.push(Token::new(
  180. "(".to_string(),
  181. TokenType::LeftParen,
  182. lineno,
  183. column,
  184. ));
  185. continue
  186. }
  187. ')' => {
  188. tokens.push(Token::new(
  189. ")".to_string(),
  190. TokenType::RightParen,
  191. lineno,
  192. column,
  193. ));
  194. continue
  195. }
  196. ',' => {
  197. tokens.push(Token::new(",".to_string(), TokenType::Comma, lineno, column));
  198. continue
  199. }
  200. ';' => {
  201. tokens.push(Token::new(
  202. ";".to_string(),
  203. TokenType::Semicolon,
  204. lineno,
  205. column,
  206. ));
  207. continue
  208. }
  209. '=' => {
  210. tokens.push(Token::new("=".to_string(), TokenType::Assign, lineno, column));
  211. continue
  212. }
  213. _ => self.error.emit(format!("Invalid token `{}`", c), lineno, column - 1),
  214. }
  215. continue
  216. }
  217. self.error.emit(format!("Invalid token `{}`", c), lineno, column - 1);
  218. }
  219. tokens
  220. }
  221. }
  222. fn is_letter(ch: char) -> bool {
  223. ('a'..='z').contains(&ch) || ('A'..='Z').contains(&ch) || ch == '_'
  224. }
  225. fn is_digit(ch: char) -> bool {
  226. ('0'..'9').contains(&ch)
  227. }