lexer.rs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use std::str::Chars;
  19. use super::error::ErrorEmitter;
  20. const SPECIAL_CHARS: [char; 7] = ['{', '}', '(', ')', ',', ';', '='];
  21. fn is_letter(ch: char) -> bool {
  22. ('a'..='z').contains(&ch) || ('A'..='Z').contains(&ch) || ch == '_'
  23. }
  24. fn is_digit(ch: char) -> bool {
  25. ('0'..='9').contains(&ch)
  26. }
  27. #[derive(Copy, Clone, PartialEq, Eq, Debug)]
  28. pub enum TokenType {
  29. Symbol,
  30. String,
  31. Number,
  32. LeftBrace,
  33. RightBrace,
  34. LeftParen,
  35. RightParen,
  36. Comma,
  37. Semicolon,
  38. Assign,
  39. }
  40. #[derive(Clone, Debug)]
  41. pub struct Token {
  42. pub token: String,
  43. pub token_type: TokenType,
  44. pub line: usize,
  45. pub column: usize,
  46. }
  47. impl Token {
  48. fn new(token: &str, token_type: TokenType, line: usize, column: usize) -> Self {
  49. Self { token: token.to_string(), token_type, line, column }
  50. }
  51. }
  52. pub struct Lexer<'a> {
  53. source: Chars<'a>,
  54. error: ErrorEmitter,
  55. }
  56. impl<'a> Lexer<'a> {
  57. pub fn new(filename: &str, source: Chars<'a>) -> Self {
  58. // For nice error reporting, we'll load everything into a string
  59. // vector so we have references to lines.
  60. let lines: Vec<String> = source.as_str().lines().map(|x| x.to_string()).collect();
  61. let error = ErrorEmitter::new("Lexer", filename, lines);
  62. Self { source, error }
  63. }
  64. pub fn lex(&self) -> Vec<Token> {
  65. let mut tokens = vec![];
  66. let mut lineno = 1;
  67. let mut column = 0;
  68. // We use this as a buffer to store a single token, which is then
  69. // reset after a token is pushed to the returning vec.
  70. let mut buf = String::new();
  71. // We use these to keep state when iterating.
  72. let mut in_comment = false;
  73. let mut in_string = false;
  74. let mut in_number = false;
  75. let mut in_symbol = false;
  76. macro_rules! new_symbol {
  77. () => {
  78. tokens.push(Token::new(&buf, TokenType::Symbol, lineno, column - buf.len()));
  79. in_symbol = false;
  80. buf = String::new();
  81. };
  82. }
  83. macro_rules! new_string {
  84. () => {
  85. tokens.push(Token::new(&buf, TokenType::String, lineno, column - buf.len()));
  86. in_string = false;
  87. buf = String::new();
  88. };
  89. }
  90. macro_rules! new_number {
  91. () => {
  92. tokens.push(Token::new(&buf, TokenType::Number, lineno, column - buf.len()));
  93. in_number = false;
  94. buf = String::new();
  95. };
  96. }
  97. #[allow(clippy::explicit_counter_loop)]
  98. for c in self.source.clone() {
  99. column += 1;
  100. if c == '\n' {
  101. if in_symbol {
  102. new_symbol!();
  103. }
  104. if in_string {
  105. self.error.abort("Strings can't contain newlines", lineno, column);
  106. }
  107. if in_number {
  108. self.error.abort("Numbers can't contain newlines", lineno, column);
  109. }
  110. in_comment = false;
  111. lineno += 1;
  112. column = 0;
  113. continue
  114. }
  115. if c == '#' || in_comment {
  116. if in_symbol {
  117. new_symbol!();
  118. }
  119. if in_number {
  120. new_number!();
  121. }
  122. if in_string {
  123. buf.push(c);
  124. continue
  125. }
  126. in_comment = true;
  127. continue
  128. }
  129. if c.is_whitespace() {
  130. if in_symbol {
  131. new_symbol!();
  132. }
  133. if in_number {
  134. new_number!();
  135. }
  136. if in_string {
  137. // TODO: Perhaps forbid whitespace.
  138. buf.push(c);
  139. }
  140. continue
  141. }
  142. // Main cases, in_comment is already checked above.
  143. if !in_number && !in_symbol && !in_string && is_digit(c) {
  144. in_number = true;
  145. buf.push(c);
  146. continue
  147. }
  148. if in_number && !is_digit(c) {
  149. new_number!();
  150. }
  151. if in_number && is_digit(c) {
  152. buf.push(c);
  153. continue
  154. }
  155. if !in_number && !in_symbol && !in_string && is_letter(c) {
  156. in_symbol = true;
  157. buf.push(c);
  158. continue
  159. }
  160. if !in_number && !in_symbol && !in_string && c == '"' {
  161. // " I need to fix my Rust vis lexer
  162. in_string = true;
  163. continue
  164. }
  165. if (in_symbol || in_string) && (is_letter(c) || is_digit(c)) {
  166. buf.push(c);
  167. continue
  168. }
  169. if in_string && c == '"' {
  170. // " I need to fix my vis lexer
  171. if buf.is_empty() {
  172. self.error.abort("String cannot be empty", lineno, column);
  173. }
  174. new_string!();
  175. continue
  176. }
  177. if SPECIAL_CHARS.contains(&c) {
  178. if in_symbol {
  179. new_symbol!();
  180. }
  181. if in_number {
  182. new_number!();
  183. }
  184. if in_string {
  185. // TODO: Perhaps forbid these chars inside strings.
  186. }
  187. match c {
  188. '{' => {
  189. tokens.push(Token::new("{", TokenType::LeftBrace, lineno, column));
  190. continue
  191. }
  192. '}' => {
  193. tokens.push(Token::new("}", TokenType::RightBrace, lineno, column));
  194. continue
  195. }
  196. '(' => {
  197. tokens.push(Token::new("(", TokenType::LeftParen, lineno, column));
  198. continue
  199. }
  200. ')' => {
  201. tokens.push(Token::new(")", TokenType::RightParen, lineno, column));
  202. continue
  203. }
  204. ',' => {
  205. tokens.push(Token::new(",", TokenType::Comma, lineno, column));
  206. continue
  207. }
  208. ';' => {
  209. tokens.push(Token::new(";", TokenType::Semicolon, lineno, column));
  210. continue
  211. }
  212. '=' => {
  213. tokens.push(Token::new("=", TokenType::Assign, lineno, column));
  214. continue
  215. }
  216. _ => self.error.abort(&format!("Invalid token `{}`", c), lineno, column - 1),
  217. }
  218. continue
  219. }
  220. self.error.abort(&format!("Invalid token `{}`", c), lineno, column - 1);
  221. }
  222. tokens
  223. }
  224. }